System.Windows.Forms.Control.Invoke(System.Delegate)

Here are the examples of the csharp api System.Windows.Forms.Control.Invoke(System.Delegate) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1060 Examples 7

19 Source : MainForm.cs
with MIT License
from CreateBrowser

public ChromiumWebBrowser AddNewBrowserTab(string url, bool focusNewTab = true, string refererUrl = null) {
			return (ChromiumWebBrowser)this.Invoke((Func<ChromiumWebBrowser>)delegate {

				// check if already exists
				foreach (FATabStripItem tab in TabPages.Items) {
					SharpTab tab2 = (SharpTab)tab.Tag;
					if (tab2 != null && (tab2.CurURL == url)) {
						TabPages.SelectedItem = tab;
						return tab2.Browser;
					}
				}

				FATabStripItem tabStrip = new FATabStripItem();
				tabStrip.replacedle = "New Tab";
				TabPages.Items.Insert(TabPages.Items.Count - 1, tabStrip);
				newStrip = tabStrip;

				SharpTab newTab = AddNewBrowser(newStrip, url);
				newTab.RefererURL = refererUrl;
				if (focusNewTab) timer1.Enabled = true;
				return newTab.Browser;
			});
		}

19 Source : FrmMain.cs
with GNU General Public License v3.0
from Crowley2012

private void UpdateCoins(string cryptoCompareResponse, string cryptoCompareCoinsResponse, string coinMarketCapResponse, List<CoinConfig> coinConfigs)
        {
            List<CoinConfig> removeConfigs = new List<CoinConfig>();
            decimal totalPaid = 0;
            decimal totalOverall = 0;
            decimal totalNegativeProfits = 0;
            decimal totalPostivieProfits = 0;
            int lineIndex = 0;

            if (string.IsNullOrWhiteSpace(cryptoCompareResponse) || string.IsNullOrWhiteSpace(cryptoCompareCoinsResponse) || string.IsNullOrWhiteSpace(coinMarketCapResponse))
            {
                MessageBox.Show("The API webservice is having issues at the moment. Please try again in a few minutes.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }

            _coinNames = MappingService.CryptoCompareCoinList(cryptoCompareCoinsResponse);
            _coins = MappingService.MapCombination(cryptoCompareResponse, coinMarketCapResponse, coinConfigs);

            MainService.CheckAlerts(_coins);

            if (_loadLines)
            {
                _cleanReset = true;
                RemoveLines();
            }

            foreach (CoinConfig coinConfig in coinConfigs)
            {
                if (!_coins.Any(c => c.ShortName == coinConfig.Name))
                {
                    Task.Factory.StartNew(() => { MessageBox.Show($"Sorry, Crypto Compare and Coin Market Cap does not have any data for {coinConfig.Name}."); });
                    removeConfigs.Add(coinConfig);
                    continue;
                }
                Coin coin = _coins.Find(c => c.ShortName == coinConfig.Name);

                if ((_cleanReset && _loadLines) || (!_coinLines.Any(c => c.CoinName.ExtEquals(coin.ShortName) && c.CoinIndex == coinConfig.Index)))
                {
                    if (_resetStartupPrice)
                        coinConfig.StartupPrice = 0;

                    AddLine(coinConfig, coin, lineIndex);
                }

                lineIndex++;

                CoinLine line = (from c in _coinLines where c.CoinName.ExtEquals(coin.ShortName) && c.CoinIndex == coinConfig.Index select c).First();

                decimal bought = line.BoughtTextBox.Text.ConvertToDecimal();
                decimal paid = line.PaidTextBox.Text.ConvertToDecimal();
                decimal total = bought * coin.Price;
                decimal profit = total - paid;

                coinConfig.Bought = bought;
                coinConfig.Paid = paid;

                totalPaid += paid;
                totalOverall += paid + profit;

                if (profit >= 0)
                    totalPostivieProfits += profit;
                else
                    totalNegativeProfits += profit;

                var coinIndexLabel = coinConfigs.Count(c => c.Name.ExtEquals(coinConfig.Name)) > 1 ? $"[{coinConfig.Index + 1}]" : string.Empty;
                var coinLabel = coin.ShortName;
                var priceLabel = $"{MainService.CurrencySymbol}{coin.Price.ConvertToString(8)}";
                var boughtLabel = $"{MainService.CurrencySymbol}{bought.SafeDivision(paid).ConvertToString(8)}";
                var totalLabel = $"{MainService.CurrencySymbol}{total:0.00}";
                var profitLabel = $"{MainService.CurrencySymbol}{profit:0.00}";
                var ratioLabel = paid != 0 ? $"{profit / paid:0.00}" : "0.00";
                var changeDollarLabel = $"{MainService.CurrencySymbol}{(coin.Price - coinConfig.StartupPrice):0.000000}";
                var changePercentLabel = $"{coinConfig.StartupPrice.SafeDivision(coin.Price - coinConfig.StartupPrice) * 100:0.00}%";
                var change1HrLabel = $"{coin.Change1HourPercent:0.00}%";
                var change24HrLabel = $"{coin.Change24HourPercent:0.00}%";
                var change7DayLabel = $"{coin.Change7DayPercent:0.00}%";

                Invoke((MethodInvoker)delegate
                {
                    line.CoinIndexLabel.Text = coinIndexLabel;
                    line.CoinLabel.Text = coinLabel;
                    line.PriceLabel.Text = priceLabel;
                    line.BoughtPriceLabel.Text = boughtLabel;
                    line.TotalLabel.Text = totalLabel;
                    line.ProfitLabel.Text = profitLabel;
                    line.RatioLabel.Text = ratioLabel;
                    line.ChangeDollarLabel.Text = changeDollarLabel;
                    line.ChangePercentLabel.Text = changePercentLabel;
                    line.Change1HrPercentLabel.Text = change1HrLabel;
                    line.Change24HrPercentLabel.Text = change24HrLabel;
                    line.Change7DayPercentLabel.Text = change7DayLabel;
                });
            }

            //Remove unsupported coins
            foreach (var coinConfig in removeConfigs)
                _coinConfigs.Remove(coinConfig);

            if (_cleanReset)
            {
                _loadLines = false;
                _resetStartupPrice = false;
            }

            _refreshTime = DateTime.Now;
            UpdateStatus("Sleeping");
            SetHeight(coinConfigs.Count);

            var totalProfitColor = totalOverall - totalPaid >= 0 ? ColorTranslator.FromHtml(UserConfigService.Theme.PositiveColor) : ColorTranslator.FromHtml(UserConfigService.Theme.NegativeColor);
            var totalProfitLabel = $"{MainService.CurrencySymbol}{totalOverall - totalPaid:0.00}";
            var totalNegativeProfitLabel = $"{MainService.CurrencySymbol}{totalNegativeProfits:0.00}";
            var totalPositiveProfitLabel = $"{MainService.CurrencySymbol}{totalPostivieProfits:0.00}";
            var totalOverallLabel = $"{MainService.CurrencySymbol}{totalOverall:0.00}";
            var totalInvested = $"{MainService.CurrencySymbol}{totalPaid:0.00}";
            var profitPercentage = $"{Math.Abs(((1 - totalPaid.SafeDivision(totalOverall))) * 100):0.00}%";

            Invoke((MethodInvoker)delegate
            {
                lblTotalProfit.ForeColor = totalProfitColor;
                lblProfitPercentage.ForeColor = totalProfitColor;
                lblTotalProfit.Text = totalProfitLabel;
                lblTotalNegativeProfit.Text = totalNegativeProfitLabel;
                lblTotalPositiveProfit.Text = totalPositiveProfitLabel;
                lblOverallTotal.Text = totalOverallLabel;
                lblTotalInvested.Text = totalInvested;
                lblProfitPercentage.Text = profitPercentage;
                alertsToolStripMenuItem.Enabled = true;
                coinsToolStripMenuItem.Enabled = true;
            });
        }

19 Source : FrmMain.cs
with GNU General Public License v3.0
from Crowley2012

private void AddLine(CoinConfig coinConfig, Coin coin, int lineIndex)
        {
            CoinLine newLine = new CoinLine(coin.ShortName, coinConfig.Index, lineIndex, Width);

            if (coinConfig.StartupPrice == 0)
                coinConfig.StartupPrice = coin.Price;

            Invoke((MethodInvoker)delegate
            {
                newLine.SetBoughtText(coinConfig.Bought.ToString());
                newLine.SetPaidText(coinConfig.Paid.ToString());

                Controls.Add(newLine.Table);
                _coinLines.Add(newLine);

                Globals.SetTheme(newLine.Table);
            });
        }

19 Source : FrmMain.cs
with GNU General Public License v3.0
from Crowley2012

private void RemoveLines()
        {
            Invoke((MethodInvoker)delegate
            {
                UpdateStatus("Loading");

                foreach (var line in _coinLines)
                    line.Dispose();

                _coinLines = new List<CoinLine>();
                SetHeight(0);
            });
        }

19 Source : FrmMain.cs
with GNU General Public License v3.0
from Crowley2012

private void UpdateRefreshTime(string time)
        {
            Invoke((MethodInvoker)delegate
            {
                txtRefreshTime.Text = time;
            });
        }

19 Source : FrmMain.cs
with GNU General Public License v3.0
from Crowley2012

private void SetHeight(int lines)
        {
            Invoke((MethodInvoker)delegate
            {
                Height = 165 + lines * 25;
            });
        }

19 Source : FrmMain.cs
with GNU General Public License v3.0
from Crowley2012

private void UpdateStatus(string status)
        {
            Invoke((MethodInvoker)delegate
            {
                lblStatus.Text = $"Status: {status}";
            });
        }

19 Source : FrmMain.cs
with GNU General Public License v3.0
from Crowley2012

private void UpdateTimers(string runningTime, string refreshTime)
        {
            Invoke((MethodInvoker)delegate
            {
                lblRunningTime.Text = runningTime;
                lblRefreshTime.Text = refreshTime;
            });
        }

19 Source : BaseForm.cs
with MIT License
from cyotek

protected virtual void EndRequest()
    {
      if (this.InvokeRequired)
      {
        this.Invoke(new MethodInvoker(this.EndRequest));
      }
      else
      {
        if (_runningRequests > 0)
        {
          _runningRequests--;
        }

        if (_runningRequests == 0)
        {
          this.UseWaitCursor = false;
          Cursor.Current = Cursors.Default;

          this.SetStatusMessage(string.Empty);
        }
      }
    }

19 Source : BaseForm.cs
with MIT License
from cyotek

protected virtual void StartRequest()
    {
      if (this.InvokeRequired)
      {
        this.Invoke(new MethodInvoker(this.StartRequest));
      }
      else
      {
        if (_runningRequests == 0)
        {
          this.UseWaitCursor = true;
          Cursor.Current = Cursors.WaitCursor;

          this.SetStatusMessage("Requesting information, please wait...");
        }

        _runningRequests++;
      }
    }

19 Source : ObjectTableControl.cs
with GNU Lesser General Public License v3.0
from czsgeo

public void ShowInfo(string info)
        {
            this.Invoke(new Action(() =>
            {
                toolStripLabel_info.Text = info;
            }));
        }

19 Source : ProgressBarComponent.cs
with GNU Lesser General Public License v3.0
from czsgeo

private void UpdateProgressBarValue()
        {
            if(CurrentPercessValue < 0) { CurrentPercessValue = 0; }

            var val = (int)(CurrentPercessValue * MultiFactorPerStep);

            if (val != this.progressBar1.Value && !this.IsDisposed)
            {
                this.Invoke(new Action(delegate()
                {
                    this.progressBar1.Value = val > this.progressBar1.Maximum ? this.progressBar1.Maximum : val;
                    if (ProgressValueChanged != null) ProgressValueChanged(this.progressBar1.Value);
                }));
            }
        }

19 Source : ProgressBarComponent.cs
with GNU Lesser General Public License v3.0
from czsgeo

public void Full() { this.Invoke(new Action(delegate() { this.progressBar1.Value = progressBar1.Maximum; ShowPersentProcessInfo(); ShowClreplacedifyInfo("完成。"); })); }

19 Source : ProgressBarComponent.cs
with GNU Lesser General Public License v3.0
from czsgeo

public void ShowPersentProcessInfo()
        {
            if (this.Created)
                this.Invoke(new Action(delegate()
                {
                    if (this.progressBar1.Value == this.progressBar1.Maximum)
                    {
                        ShowInfo(CurrentClreplacedify + " 执行完毕!");
                    }

                    this.label_progressPersent.Text = this.progressBar1.Value + "/" + this.progressBar1.Maximum;
                    this.label_progressPersent.Update();
                }));
        }

19 Source : FormUtil.cs
with GNU Lesser General Public License v3.0
from czsgeo

public static void InvokeTextBoxSetText(TextBoxBase textBox, string str, bool isAppend = false)
        {
            try
            {
                textBox.Invoke(new Action(delegate()
                {
                    if (isAppend)
                        textBox.Text += str;
                    else textBox.Text = str;
                }));

            }
            catch (Exception ex) { }
        }

19 Source : ObsFileSelectorForm.cs
with GNU Lesser General Public License v3.0
from czsgeo

private void Process(string subDir, ObsFileSelectOption opt, string inputPath)
        {
            ShowInfo("processing :" + inputPath);

            if (ObsFileSelector.Select(inputPath, subDir))
            {
                SelectedCount++;
            }
             

            this.Invoke(new Action(() =>
            {
                this.progressBar1.PerformStep();
                this.progressBar1.Refresh();
            }));
        }

19 Source : ProgressBarComponent.cs
with GNU Lesser General Public License v3.0
from czsgeo

public void InitNextClreplacedProcessCount(long nextProcessCount)
        {
            if (!this.IsHandleCreated) { return; }

            this.Invoke(new Action(delegate ()
            {
                if (!IsBackwardProcess)
                {
                    this.CurrentPercessValue = 0;
                    this.SetProgressCount(nextProcessCount);
                    this.progressBar1.Minimum = 0;
                    this.progressBar1.Value = this.progressBar1.Minimum;
                }
                else
                {
                    this.CurrentPercessValue = nextProcessCount;
                    this.SetProgressCount(nextProcessCount);
                    this.progressBar1.Minimum = 0;
                    this.progressBar1.Value = this.progressBar1.Maximum;
                }
            }));
            ShowInfo("当前进度 ");
            ShowClreplacedifyInfo();
        }

19 Source : FormUtil.cs
with GNU Lesser General Public License v3.0
from czsgeo

public static void InsertLineToTextBox(TextBoxBase textBoxBase, string info, int maxAllowCount = 5000)
        {
            try
            {
                if (textBoxBase == null || textBoxBase.IsDisposed)
                {
                    return;
                }
                textBoxBase.Invoke(new Action(delegate()
                {
                    var count = textBoxBase.Lines.Length;

                    if (count >= maxAllowCount)
                    {
                        List<string> lines = new List<string>(textBoxBase.Lines);
                        lines.RemoveAt(count - 1);
                        lines.Insert(0, info);
                        textBoxBase.Lines = lines.ToArray();
                    }
                    else
                    {
                        textBoxBase.Text = info + "\r\n" + textBoxBase.Text;
                    }

                }));
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
            }
        }

19 Source : FormUtil.cs
with GNU Lesser General Public License v3.0
from czsgeo

public static void SetText(Control control, string text)
        {
            try
            {
                if (control.IsHandleCreated)
                {
                    control.Invoke(new Action(delegate()
                    {
                        control.Text = text;
                    }));
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
            }
        }

19 Source : FileInfoExtractForm.cs
with GNU Lesser General Public License v3.0
from czsgeo

private void ShowInfo(string info)
        {
            this.Invoke(new Action(() =>
            {
                this.label_info.Text = info;
            }));
        }

19 Source : FileInfoExtractForm.cs
with GNU Lesser General Public License v3.0
from czsgeo

private void Run()
        {
            table = new ObjectTableStorage();

            var InputRawPathes = this.fileOpenControl1.FilePathes;

            this.Invoke(new Action(() =>
            {
                this.progressBar1.Maximum = InputRawPathes.Length;
                this.progressBar1.Minimum = 0;
                this.progressBar1.Value = 0;
                this.progressBar1.Step = 1;
            }));

            foreach (var inputPath in InputRawPathes)
            {
                if (IsCancel)
                {
                    ShowInfo("Canceled at :" + inputPath);
                    break;
                }
                string subDir = Gdp.Utils.PathUtil.GetSubDirectory(InputRawPathes, inputPath);

                Process(subDir, inputPath);
            }
        }

19 Source : FileInfoExtractForm.cs
with GNU Lesser General Public License v3.0
from czsgeo

private void Process(string subDir, string inputPath)
        {
            try
            {
                ShowInfo("processing :" + inputPath);

                var header = RinexObsFileReader.ReadHeader(inputPath);
                var siteInfo = header.SiteInfo;
                var obsInfo = header.ObsInfo;
                table.NewRow();
                if (IsLonLatFirst)
                {
                    table.AddItem("Lon", siteInfo.ApproxGeoCoord.Lon);
                    table.AddItem("Lat", siteInfo.ApproxGeoCoord.Lat);
                    table.AddItem("Name", siteInfo.SiteName);
                }
                else
                {
                    table.AddItem("Name", siteInfo.SiteName);
                    table.AddItem("Lon", siteInfo.ApproxGeoCoord.Lon);
                    table.AddItem("Lat", siteInfo.ApproxGeoCoord.Lat);
                }
                table.AddItem("Height", siteInfo.ApproxGeoCoord.Height);
                table.AddItem("X", siteInfo.ApproxXyz.X);
                table.AddItem("Y", siteInfo.ApproxXyz.Y);
                table.AddItem("Z", siteInfo.ApproxXyz.Z);
                table.AddItem("ReceiverType", siteInfo.ReceiverType);
                table.AddItem("ReceiverNumber", siteInfo.ReceiverNumber);
                table.AddItem("AntennaType", siteInfo.AntennaType);
                table.AddItem("AntennaNumber", siteInfo.AntennaNumber);


                this.Invoke(new Action(() =>
                {
                    this.progressBar1.PerformStep();
                    this.progressBar1.Refresh();
                }));
            }
            catch (Exception ex)
            {
                log.Error("转换出错:\t" + inputPath + "\t, " + ex.Message);
            }
        }

19 Source : IgsProductDownloadForm.cs
with GNU Lesser General Public License v3.0
from czsgeo

private void ShowInfo(string url)
        {
            this.Invoke(new Action(delegate()
            {
                this.textBox_result.Text = DateTime.Now + ":" + url + "\r\n" + this.textBox_result.Text;
                this.textBox_result.Update();
            }));
        }

19 Source : IgsProductDownloadForm.cs
with GNU Lesser General Public License v3.0
from czsgeo

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                if (!Directory.Exists(SaveDir)) Directory.CreateDirectory(SaveDir);

                List<string> failed = new List<string>();
                int okCount = 0;
                foreach (string url in FileUrls)
                {
                    string info = "Downloading successfully!";
                    if (IsCancel || backgroundWorker1.CancellationPending)
                    {
                        ShowInfo("Downloading ending!");
                        break;
                    }
                    if (!Gdp.Utils.NetUtil.FtpDownload(url, Path.Combine(SaveDir, Path.GetFileName(url))))
                    {
                        failed.Add(url);
                        info = "Downloading Filed!";
                    }
                    else
                    {
                        okCount++;
                    }
                    ShowInfo(info + url);

                    this.Invoke(new Action(PerformStep));
                }
                //outputing the failed pathes
                StringBuilder sb = new StringBuilder();
                foreach (string fail in failed)
                {
                    sb.AppendLine(fail);
                }
                if (sb.Length > 0)
                {
                    this.Invoke(new Action(delegate()
                    {
                        this.richTextBoxControl_failedUrls.Text = sb.ToString();
                    }));
                    ShowInfo("The failed pathes are \r\n" + sb.ToString());
                }

                String msg = "Finsh download, wherein " + FileUrls.Length + " files download successfully." + okCount + " \r\n And " + failed.Count + " files failed.\r\n";

                msg += "\r\n是否打开目录?";
                Gdp.Utils.FormUtil.ShowIfOpenDirMessageBox(SaveDir, msg);
            }
            catch (Exception ex)
            {
                MessageBox.Show(" %>_<% Error!" + ex.Message);
            }
        }

19 Source : ObsFileConvertForm.cs
with GNU Lesser General Public License v3.0
from czsgeo

private void Run()
        {
            var InputRawPathes = this.fileOpenControl1.FilePathes;
            ObsFileConvertOption opt = GetOrInitObsFileFormatOption();

            this.Invoke(new Action(() =>
            {
                this.progressBar1.Maximum = InputRawPathes.Length;
                this.progressBar1.Minimum = 0;
                this.progressBar1.Value = 0;
                this.progressBar1.Step = 1;
            }));

            if (IsParallel)
            {
                var count = namedIntControl_processCount.GetValue();
                ParallelOptions parallelOptions = new ParallelOptions() { MaxDegreeOfParallelism = count };
                Parallel.ForEach(InputRawPathes, parallelOptions, (inputPath, state) =>
                {
                    if (IsCancel || this.backgroundWorker1.CancellationPending) { ShowInfo("Canceled at :" + inputPath); state.Stop(); }

                    string subDir = Gdp.Utils.PathUtil.GetSubDirectory(InputRawPathes, inputPath);

                    Process(subDir, opt, inputPath);
                });
            }
            else
            {
                foreach (var inputPath in InputRawPathes)
                {
                    if (IsCancel)
                    {
                        ShowInfo("Canceled at :" + inputPath);
                        break;
                    }
                    string subDir = Gdp.Utils.PathUtil.GetSubDirectory(InputRawPathes, inputPath);

                    Process(subDir, opt, inputPath);
                }

                Complete();

            }
        }

19 Source : ObsFileConvertForm.cs
with GNU Lesser General Public License v3.0
from czsgeo

private void Process(string subDir, ObsFileConvertOption opt, string inputPath)
        {
            try
            {
                ShowInfo("processing :" + inputPath);

                ObsFileFormater ObsFileFormater = new ObsFileFormater(opt, inputPath);
                CurrentRunners.Add(ObsFileFormater);
                ObsFileFormater.SubDirectory = subDir;
                ObsFileFormater.Init();
                ObsFileFormater.Run();
                CurrentRunners.Remove(ObsFileFormater);
                this.Invoke(new Action(() =>
                {
                    this.progressBar1.PerformStep();
                    this.progressBar1.Refresh();
                }));
            }catch(Exception ex)
            {
                log.Error("转换出错:\t" + inputPath + "\t, "+ ex.Message );
            }
        }

19 Source : TableObjectViewForm.cs
with GNU Lesser General Public License v3.0
from czsgeo

public void ShowInfo(string info)
        {
            this.Invoke(new Action(() =>
            {
                objectTableControl1.ShowInfo(info);
             //   toolStripLabel_info.Text = info;
            }));
        }

19 Source : ObsFileViewerForm.cs
with GNU Lesser General Public License v3.0
from czsgeo

public void ShowInfo(string info)
        {
            this.Invoke(new Action(delegate ()
            {
                toolStripLabel1.Text = info;
            }));
        }

19 Source : ObsFileSelectorForm.cs
with GNU Lesser General Public License v3.0
from czsgeo

private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            var InputRawPathes = this.fileOpenControl1.FilePathes; 


            ShowInfo("Start execution");
            this.ObsFileSelectOption = GetOrInitObsFileSelectOption();
            SelectedCount = 0;


            this. ObsFileSelector = new ObsFileSelector(ObsFileSelectOption, OutputDirectory);
     
   
            this.Invoke(new Action(() =>
            {
                this.progressBar1.Maximum = InputRawPathes.Length;
                this.progressBar1.Minimum = 0;
                this.progressBar1.Step = 1;
            }));

            if (IsParallel)
            {
                var count = namedIntControl_processCount.GetValue();
                ParallelOptions parallelOptions = new ParallelOptions() { MaxDegreeOfParallelism = count };
                Parallel.ForEach(InputRawPathes, parallelOptions, (inputPath, state) =>

                {
                    if (IsCancel || this.backgroundWorker1.CancellationPending) { ShowInfo("Canceled at :" + inputPath); state.Stop(); }

                  string subDir = Gdp.Utils.PathUtil.GetSubDirectory(InputRawPathes, inputPath);

                  Process(subDir, ObsFileSelectOption, inputPath);
              });

            }
            else
            {
                foreach (var inputPath in InputRawPathes)
                {
                    if (IsCancel)
                    {
                        ShowInfo("Canceled at :" + inputPath);
                        break;
                    }
                    string subDir = Gdp.Utils.PathUtil.GetSubDirectory(InputRawPathes, inputPath);

                    Process(subDir, ObsFileSelectOption, inputPath);
                }
            }
        }

19 Source : Encoder.cs
with GNU General Public License v3.0
from DaGooseYT

internal static void WhileWorking(FFLoaderBase ffLoader, ComboBox preset, ComboBox tune, ComboBox algo, ComboBox format, ComboBox sr, 
            ComboBox mode, ComboBox abitrate, ProgressBarLabel pb, int fmode, double frameRate, double bframe, double vbitrate, double crf, 
            double height, double width, float sharpen, string version, bool mute)
        {
            EncodePB = pb;
            FFloader = ffLoader;

            //Prevents cross-threading errors.
            if (fmode == 0)
            {
                preset.Invoke(new Action(() => { Preset = preset.SelectedItem; }));
                tune.Invoke(new Action(() => { Tune = tune.SelectedItem; }));
                algo.Invoke(new Action(() => { ResizeAlgo = algo.SelectedItem; }));
                format.Invoke(new Action(() => { AudioFormat = format.SelectedItem; }));
                abitrate.Invoke(new Action(() => { AudioBitrate = abitrate.SelectedItem; }));
                sr.Invoke(new Action(() => { AudioSR = sr.SelectedItem; }));
                mode.Invoke(new Action(() => { Mode = mode.SelectedItem; }));
            }

            //Subcribe to events.
            ffLoader.FFConversionProgress += UpdateProgress;
            ffLoader.FFLoaderException += FFException;
            ffLoader.AviSynthError += AvsError;
            ffLoader.FFMpegError += FFError;

            try
            {
                if (fmode == 0)
                {
                    ffLoader.ConvertFFMpeg("libx264", Mode.ToString(), Preset.ToString(), Tune.ToString(), ResizeAlgo.ToString(), AudioFormat.ToString(),
                    AudioBitrate.ToString(), AudioSR.ToString(), height, width, vbitrate, frameRate, bframe, crf, sharpen, version, mute);
                }
                else
                {
                    ffLoader.ConvertOneClick("libx264", version);
                }
            }
            catch (IOException)
            {
                MessageBox.Show("FrameGUI is already open and working on a process. Please close any other running tasks of FrameGUI before starting a new process.", "FrameGUI error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                
                EncodePB.Invoke(new Action(() =>
                {
                    EncodePB.ProgressText = "Process exited because FrameGUI is already open.";
                }));
                
                EncodePB.TextColor = Color.Red;
            }
        }

19 Source : Splasher.cs
with GNU General Public License v3.0
from dahai202

public static void Close()
        {
            if (m_SplashThread == null || m_SplashForm == null) return;

            try
            {
                m_SplashForm.Invoke(new MethodInvoker(m_SplashForm.Close));
            }
            catch (Exception)
            {
            }
            m_SplashThread = null;
            m_SplashForm = null;
        }

19 Source : BufferedPainter.cs
with MIT License
from dahall

private void CleanupAnimations()
		{
			if (Control.InvokeRequired)
			{
				Control.Invoke(new MethodInvoker(CleanupAnimations));
			}
			else if (animationsNeedCleanup)
			{
				if (Control.IsHandleCreated) BufferedPaintStopAllAnimations(new HandleRef(Control, Control.Handle));
				BufferedPaintUnInit();
				animationsNeedCleanup = false;
			}
		}

19 Source : HardwareUsageViewer.cs
with BSD 3-Clause "New" or "Revised" License
from DannyTheSloth

private void bwUpdateCharts_DoWork(object sender, DoWorkEventArgs e)
        {
            while (Update)
            {
                Invoke(new MethodInvoker(() =>
                {
                    try
                    {
                        int CpuUsage = Convert.ToInt32(txtCpuUsage.Text);
                        ucCpu.Series[0].Points.AddY(CpuUsage);
                        if (ucCpu.Series[0].Points.Count > 40)
                            ucCpu.Series[0].Points.RemoveAt(0);
                        int DiskUsage = Convert.ToInt32(txtDiskUsage.Text);
                        ucDisk.Series[0].Points.AddY(DiskUsage);
                        if (ucDisk.Series[0].Points.Count > 40)
                            ucDisk.Series[0].Points.RemoveAt(0);
                    }
                    catch { }
                }));
                Thread.Sleep(450);
            }
        }

19 Source : CNetworkSettings.cs
with GNU General Public License v3.0
from DarwinBaker

public void SetControlStates(string buttonText, bool enableButton, bool enableDropDown)
        {
            if (this.IsDisposed)
                return;
            try
            {
                //update network switch button on main thread
                this.Invoke((MethodInvoker)delegate {
                    this.networkSwitch.Text = buttonText;
                    this.networkSwitch.Enabled = enableButton;
                    this.networkType.Enabled = enableDropDown;
                    this.UpdateEnabledStates();
                });
            }
            catch { }
        }

19 Source : CNetworkSettings.cs
with GNU General Public License v3.0
from DarwinBaker

public void SyncConsole()
        {
            if (this.IsDisposed)
                return;
            try
            {
                //update console on ui thread
                this.Invoke((MethodInvoker)delegate {
                    this.GetConsole().Text = Peer.IsRunning 
                        ? Peer.Instance.ConsoleOutput 
                        : string.Empty;
                });
            }
            catch { }
        }

19 Source : CNetworkSettings.cs
with GNU General Public License v3.0
from DarwinBaker

public void SyncUserList(IEnumerable<User> users)
        {
            if (this.IsDisposed)
                return;
            try
            {
                //update network switch button on ui thread
                this.Invoke((MethodInvoker)delegate {
                    this.GetUserList().Items.Clear();
                    foreach (User user in users)
                    {
                        var item = new ListViewItem() {
                            Text = user.Name,
                            Tag  = user.Id
                        };
                        this.GetUserList().Items.Add(item);
                    }
                });
            }
            catch { }
        }

19 Source : CNetworkSettings.cs
with GNU General Public License v3.0
from DarwinBaker

public void WriteToConsole(string line)
        {
            if (this.IsDisposed)
                return;
            try
            {
                //update console on ui thread
                this.Invoke((MethodInvoker)delegate {
                    if (string.IsNullOrEmpty(this.GetConsole().Text))
                        this.SyncConsole();
                    this.GetConsole().AppendText(line + "\n");
                });
            }
            catch { }
        }

19 Source : FormAccountDetails.cs
with MIT License
from dathlin

private void ThreadPoolLoadLargePortrait(object obj)
        {
            // 先获取服务器端的MD5码
            string fileServerMd5 = UserClient.UserAccount.LargePortraitMD5;
            if (string.IsNullOrEmpty(fileServerMd5))
            {
                return; // 没有文件
            }

            string fileName = Application.StartupPath + @"\Portrait\" + UserClient.UserAccount.UserName + @"\" + PortraitSupport.LargePortrait;
            if(File.Exists(fileName))
            {
                bool loadSuccess = false;
                Invoke(new Action(() =>
                {
                    try
                    {
                        pictureBox_UserPortrait.Image = new Bitmap(new MemoryStream(File.ReadAllBytes(fileName)));
                        loadSuccess = true;
                    }
                    catch
                    {

                    }
                }));

                if (!loadSuccess) goto P1; // 加载不成功,直接重新下载

                // 计算md5
                string md5 = string.Empty;

                try
                {
                    md5 = SoftBasic.CalculateFileMD5(fileName);
                }
                catch
                {

                }

                if(md5 == UserClient.UserAccount.LargePortraitMD5)
                {
                    return;
                }
            }
            
            P1:
            MemoryStream ms = new MemoryStream();
            OperateResult result = UserClient.Net_File_Client.DownloadFile(
                PortraitSupport.LargePortrait,
                "Files",
                "Portrait",
                UserClient.UserAccount.UserName, 
                null,
                ms
                );

            if (result.IsSuccess)
            {
                try
                {
                    if (IsHandleCreated) Invoke(new Action(() =>
                    {
                        // 下载完成
                        Bitmap bitmap = new Bitmap(ms);
                        pictureBox_UserPortrait.Image = bitmap;
                        bitmap.Save(fileName);
                    }));
                }
                catch
                {
                    // 不知道什么原因 
                }
            }
            else
            {
                // 下载异常,丢弃
            }

            ms.Dispose();
        }

19 Source : FormDownloading.cs
with MIT License
from dathlin

private void ThreadRequestServer()
        {
            //后台请求数据
            System.Threading.Thread.Sleep(100);
            OperateResult<string> result = UserClient.Net_simplify_client.ReadFromServer(net_cmd);
            Invoke(new Action(() =>
            {
                DealWithResult(result);
                time.Stop();
                System.Threading.Thread.Sleep(20);
                Dispose();
            }));
        }

19 Source : FileItemShow.cs
with MIT License
from dathlin

private void ThreadDownloadFile()
        {
            string save_file_name = Application.StartupPath + "\\download\\files";
            if (!Directory.Exists(save_file_name))
            {
                Directory.CreateDirectory(save_file_name);
            }
            save_file_name += "\\" + fileItem.FileName;


            OperateResult result = fileClient.DownloadFile(
                fileItem.FileName,
                m_Factory,
                m_Group,
                m_Id,
                DownloadProgressReport, 
                save_file_name
                );

            if(IsHandleCreated) Invoke(new Action(() =>
            {
                if(result.IsSuccess)
                {
                    if (MessageBox.Show("下载完成,路径为:" + save_file_name + Environment.NewLine +
                        "是否打开文件路径?", "打开确认", MessageBoxButtons.YesNo,
                        MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        System.Diagnostics.Process.Start("explorer.exe", @"/select," + save_file_name);
                    }
                }
                else
                {
                    MessageBox.Show("下载失败,错误原因:" + result.Message);
                }
                if (IsHandleCreated) linkLabel_download.Enabled = true;
            }));
        }

19 Source : FormAccountDetails.cs
with MIT License
from dathlin

private void treeView1_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] paths = e.Data.GetData(DataFormats.FileDrop) as string[];
                if (paths != null)
                {
                    List<string> files = new List<string>();

                    try
                    {
                        foreach (var m in paths)
                        {
                            FileInfo finfo = new FileInfo(m);
                            if (finfo.Attributes == FileAttributes.Directory)
                            {
                                foreach (var n in Directory.GetFiles(m))
                                {
                                    files.Add(n);
                                }
                            }
                            else
                            {
                                files.Add(m);
                            }
                        }
                    }
                    catch(Exception ex)
                    {
                        UserClient.LogNet?.WriteException("拖拽文件上传异常:", ex);
                        SoftBasic.ShowExceptionMessage(ex);
                        return;
                    }

                    if (files.Count > 0)
                    {
                        Invoke(new Action(() =>
                        {
                            UploadFilesToServer(files.ToArray());
                        }));
                    }
                }
                
            }
        }

19 Source : FileOperateControl.cs
with MIT License
from dathlin

private void WrongTextShow(string text)
        {
            if (IsHandleCreated && InvokeRequired)
            {
                Invoke(new Action(() =>
                {
                    WrongTextShow(text);
                }));
                return;
            }

            label_now_info.Text = text;
            button1.Visible = true;
            IsOperateFinished = true;
            progressBar1.Value = 0;
        }

19 Source : FileOperateControl.cs
with MIT License
from dathlin

private void ReportProgress(long current,long count)
        {
            Invoke(new Action(() =>
            {
                long percent = 0;
                if (count > 0)
                {
                    percent = current * 100 / count;
                }

                progressBar1.Value = (int)percent;
                label_now_info.Text = "已完成:" + percent.ToString() + "%";

                label_filesize.Text = SoftBasic.GetSizeDescription(count);
            }));
        }

19 Source : FileOperateControl.cs
with MIT License
from dathlin

private void ThreadDownloadFile()
        {
            Invoke(new Action(() =>
            {
                label_now_info.Text = "正在下载文件...";
                progressBar1.Value = 0;
            }));


            if (!SavaPathDirectory.EndsWith(@"\"))
            {
                SavaPathDirectory = SavaPathDirectory + @"\";
            }

            

            OperateResult result = AdvancedFileClient.DownloadFile(
                FilePath,
                Factory,
                Group,
                Id,
                ReportProgress,
                SavaPathDirectory + FilePath
                );

            if(result.IsSuccess)
            {
                Invoke(new Action(() =>
                {
                    label_now_info.Text = "文件下载成功";
                }));
            }
            else
            {
                WrongTextShow("异常:" + result.Message);
            }

            IsOperateFinished = true;
        }

19 Source : FormMainWindow.cs
with MIT License
from dathlin

private void Net_socket_client_AcceptString(AppSession session, NetHandle customer, string data)
        {
            if (customer == CommonHeadCode.MultiNetHeadCode.弹窗新消息)
            {
                if (IsHandleCreated) Invoke(new Action(() =>
                {
                    FormPopup fpp = new FormPopup(data, Color.DodgerBlue, 10000);
                    fpp.Show();
                }));
            }
            else if (customer == CommonHeadCode.MultiNetHeadCode.总在线信息)
            {
                //if (IsHandleCreated) Invoke(new Action(() =>
                //{
                //    // listBox1.DataSource = data.Split('#');

                //    NetAccount[] accounts = JArray.Parse(data).ToObject<NetAccount[]>();

                //    netClientOnline1.SetOnlineRender(accounts);
                //}));
            }
            else if (customer == CommonHeadCode.MultiNetHeadCode.关闭客户端)
            {
                if (IsHandleCreated) Invoke(new Action(() =>
                {
                    Close();
                }));
            }
            else if (customer == CommonHeadCode.SimplifyHeadCode.更新公告)
            {
                //此处应用到了同步类的指令头
                if (IsHandleCreated) Invoke(new Action(() =>
                {
                    UserClient.Announcement = data;
                    label_Announcement.Text = data;
                    FormPopup fpp = new FormPopup(data, Color.DodgerBlue, 10000);
                    fpp.Show();
                }));
            }
            else if (customer == CommonHeadCode.MultiNetHeadCode.初始化数据)
            {
                //收到服务器的数据
                JObject json = JObject.Parse(data);
                UserClient.DateTimeServer = json["Time"].ToObject<DateTime>();
                List<string> chats = JArray.Parse(json["chats"].ToString()).ToObject<List<string>>();
                StringBuilder sb = new StringBuilder();
                chats.ForEach(m => { sb.Append(m + Environment.NewLine); });


                if (IsHandleCreated) Invoke(new Action(() =>
                {
                    toolStripStatusLabel_time.Text = UserClient.DateTimeServer.ToString("yyyy-MM-dd HH:mm:ss");
                    label_file_count.Text = json["FileCount"].ToObject<int>().ToString();
                    UIControls_Chat.AddChatsHistory(sb.ToString());

                    UserClient.LogNet?.WriteDebug("Online Clients : " + json["ClientsOnline"].ToString());
                    NetAccount[] accounts = JArray.Parse(json["ClientsOnline"].ToString()).ToObject<NetAccount[]>();
                    netClientOnline1.SetOnlineRender(accounts);
                }));
            }
            else if (customer == CommonHeadCode.MultiNetHeadCode.文件总数量)
            {
                if (IsHandleCreated) Invoke(new Action(() =>
                {
                    label_file_count.Text = data;
                }));
            }
            else if (customer == CommonHeadCode.MultiNetHeadCode.留言版消息)
            {
                if (IsHandleCreated) Invoke(new Action(() =>
                {
                    UIControls_Chat?.DealwithReceive(data);
                }));
            }
            else if(customer == CommonHeadCode.MultiNetHeadCode.新用户上线)
            {
                if (IsHandleCreated) Invoke(new Action(() =>
                {
                    UserClient.LogNet?.WriteDebug("Online Event : " + data);
                    netClientOnline1.ClientOnline(JObject.Parse(data).ToObject<NetAccount>());
                }));
            }
            else if(customer == CommonHeadCode.MultiNetHeadCode.用户下线)
            {
                if (IsHandleCreated) Invoke(new Action(() =>
                {
                    netClientOnline1.ClinetOffline(data);
                }));
            }
            else if(customer == CommonHeadCode.MultiNetHeadCode.新头像更新)
            {
                UserClient.PortraitManager.UpdateSmallPortraitByName(data);
                if (IsHandleCreated) Invoke(new Action(() =>
                {
                    if(data == UserClient.UserAccount.UserName)
                    {
                        pictureBox1.Image = UserClient.PortraitManager.GetSmallPortraitByUserName(data);
                    }
                    netClientOnline1.ClientUpdatePortrait(data);
                }));
            }
        }

19 Source : FileOperateControl.cs
with MIT License
from dathlin

private void ThreadUploadFile()
        {
            FileInfo finfo = new FileInfo(FilePath);

            Invoke(new Action(() =>
            {
                label_now_info.Text = "正在上传文件...";
                label_filesize.Text = SoftBasic.GetSizeDescription(finfo.Length);
                progressBar1.Value = 0;
            }));

            OperateResult result = AdvancedFileClient.UploadFile(
                FilePath,
                finfo.Name,
                Factory,
                Group,
                Id,
                "",
                UserClient.UserAccount.UserName,
                ReportProgress);

            if (result.IsSuccess)
            {
                Invoke(new Action(() =>
                {
                    label_now_info.Text = "文件上传成功";
                }));
            }
            else
            {
                WrongTextShow("异常:" + result.Message);
            }

            IsOperateFinished = true;
        }

19 Source : FormFileOperate.cs
with MIT License
from dathlin

private void ThreadCheckFinish()
        {
            Thread.Sleep(400);

            Invoke(new Action(() =>
            {
                label1.Text += all_file_controls.Count;
                label_finish.Text = "0/" + all_file_controls.Count;

                for (int i = 0; i < all_file_controls.Count; i++)
                {
                    if (is_down_file)
                    {
                        all_file_controls[i].StartDownloadFile();
                    }
                    else
                    {
                        all_file_controls[i].StartUploadFile();
                    }
                }
            }));
            Thread.Sleep(400);
            while (true)
            {
                int complete = 0;
                for (int i = 0; i < all_file_controls.Count; i++)
                {
                    if (all_file_controls[i].IsOperateFinished)
                    {
                        complete++;
                    }
                }

                try
                { 
                    // 更新显示进度
                    Invoke(new Action(() =>
                    {
                        label_finish.Text = complete + "/" + all_file_controls.Count;
                    }));
                }
                catch
                {

                }
                
                if (complete >= all_file_controls.Count)
                {
                    break;
                }
                Thread.Sleep(490);
            }
        }

19 Source : FormMainWindow.cs
with MIT License
from dathlin

private void Net_socket_client_LoginSuccess()
        {
            // 登录成功,或重新登录成功的事件,有些数据的初始化可以放在此处
            if (IsHandleCreated) Invoke(new Action(() =>
            {
                toolStripStatusLabel_status.Text = "客户端启动成功";
            }));
        }

19 Source : FormMainWindow.cs
with MIT License
from dathlin

private void Net_socket_client_MessageAlerts(string object1)
        {
            // 信息提示
            if (IsHandleCreated) Invoke(new Action(() =>
            {
                toolStripStatusLabel_status.Text = object1;
            }));
        }

19 Source : FormMainWindow.cs
with MIT License
from dathlin

public void ThreadTimeTick()
        {
            Thread.Sleep(300);//加一个微小的延时
            int second = DateTime.Now.Second - 1;
            int minute = -1;
            int hour = -1;
            int day = -1;
            Action DTimeShow = delegate
            {
                //显示服务器的时间和当前网络的延时时间,通常为毫秒
                toolStripStatusLabel_time.Text = net_socket_client.ServerTime.ToString("yyyy-MM-dd HH:mm:ss") + $"({net_socket_client.DelayTime}ms)";
            };

            while (IsWindowShow)
            {
                while (DateTime.Now.Second == second)
                {
                    Thread.Sleep(20);
                }
                second = DateTime.Now.Second;
                if (IsWindowShow && IsHandleCreated) Invoke(DTimeShow);
                // 每秒钟执行的代码
                UserClient.DateTimeServer = net_socket_client.ServerTime;

                if (second == 0)
                {
                    // 每个0秒执行的代码
                }

                if (minute != DateTime.Now.Minute)
                {
                    minute = DateTime.Now.Minute;
                    // 每分钟执行的代码
                }

                if (hour != DateTime.Now.Hour)
                {
                    hour = DateTime.Now.Hour;
                    // 每小时执行的代码
                }

                if (day != DateTime.Now.Day)
                {
                    day = DateTime.Now.Day;
                    // 每天执行的代码
                }
            }
        }

See More Examples