System.Windows.Forms.Control.Invoke(System.Delegate, params object[])

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

643 Examples 7

19 View Source File : Form1.cs
License : Apache License 2.0
Project Creator : becomequantum

private void AppendText(RichTextBox richtextbox, string text)
        {
            if (richtextbox.InvokeRequired)
            {
                AppendTextDelegate d = AppendText;
                richtextbox.Invoke(d, new object[] { richtextbox, text });
            }
            else
            {
                richtextbox.AppendText(text + "\n");
            }
        }

19 View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : boonkerz

void Network_OnConnected(object sender, ConnectedEventArgs e)
        {
            if (this.txtSystemId.InvokeRequired)
            {
                SetSystemIdAndPreplacedwordCallback d = new SetSystemIdAndPreplacedwordCallback(SetSystemIdAndPreplacedword);
                this.Invoke(d, new object[] { e.SystemId, hostThread.Manager.Preplacedword });
            }
            else
            {
                SetSystemIdAndPreplacedword(e.SystemId, hostThread.Manager.Preplacedword);
            }
        }

19 View Source File : FormGUI.cs
License : MIT License
Project Creator : AndnixSH

public void Log(string text, Color? color = null)
        {
            Invoke(new Action(delegate ()
            {
                richTextBoxLogs.SelectionColor = color ?? Color.White;
                richTextBoxLogs.AppendText(text + Environment.NewLine);
            }));
        }

19 View Source File : WaveForm.cs
License : MIT License
Project Creator : azist

private void setControlEnabled(bool enabled)
    {
      if (this.InvokeRequired)
      {
        var cb = new Action<bool>(setControlEnabled);
        this.Invoke(cb, enabled);
      }
      else
      {
        pnlManage.Controls.OfType<Control>().ForEach(c => c.Enabled = enabled);
        btnCancel.Enabled = !enabled;
        tmrUpdate.Enabled = !enabled;
      }
    }

19 View Source File : FormsHelper.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public static object Invoke(
            Control control,
            Action action,
            params object[] args)
        {
            if (control == null ||
                control.IsDisposed ||
                !control.IsHandleCreated)
            {
                return null;
            }

            if (control.InvokeRequired)
            {
                return control.Invoke(action, args);
            }
            else
            {
                action();
                return null;
            }
        }

19 View Source File : CustomParamsUseBotSample.cs
License : Apache License 2.0
Project Creator : AlexWan

private void PaintTable(List<Candle> candles)
        {
            if(_grid.InvokeRequired)
            {
                _grid.Invoke(new Action<List<Candle>>(PaintTable), candles);
                return;
            }

            _grid.Rows.Clear();

            List<decimal> smaFast = _fastSma.DataSeries[0].Values;
            List<decimal> smaSlow = _slowSma.DataSeries[0].Values;
            List<decimal> atr = _atr.DataSeries[0].Values;


            for (int i = 0;i < candles.Count;i++)
            {
                _grid.Rows.Add(GetRow(candles[i], smaSlow[i], smaFast[i], atr[i]));

            }

        }

19 View Source File : MainForm.cs
License : MIT License
Project Creator : bestyize

private void displayReceiveData(object obj)
        {
            if (tb_recv.InvokeRequired)
            {
                var d = new SafeCallDelegate(displayReceiveData);
                Invoke(d, new object[] { obj });
            }
            else {
                if (cbox_hex_display.Checked)
                {
                    
                    tb_recv.AppendText(" " + convertToHexString((string)obj));
                    label_recv_count.Text = "R:" + (tb_recv.Text.Length + 1) / 3;
                }
                else {
                    
                    tb_recv.AppendText((string)obj);
                    label_recv_count.Text = "R:" + tb_recv.Text.Length;

                }
                
            }
            
        }

19 View Source File : Controlpanel.cs
License : MIT License
Project Creator : alexwahl

public  void ReceivedFrequencyInHzChanged(long frequency_in_hz)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<long>(ReceivedFrequencyInHzChanged), new object[] { frequency_in_hz });
                return;
            }
            else
            {
                this.labelFrequency.Text = frequency_in_hz.ToString();
            }
        }

19 View Source File : manager.cs
License : BSD 2-Clause "Simplified" License
Project Creator : chengse66

private void enumerate_accessory(wzpackage host, wzproperty idenreplacedies, res_commodity commodities, res_objects accessory, res_root res)
	{
		string location = thumbnails + "character\\accessory\\";

		Directory.CreateDirectory(location);

		foreach (wzpackage package in host)
		{
			if (null == thread)
				break;

			if (package.idenreplacedy.StartsWith("0101") || package.idenreplacedy.StartsWith("0102") || package.idenreplacedy.StartsWith("0103"))
			{
				string idenreplacedy = package.idenreplacedy.Substring(0, 8);

				if (!res["character", "accessory", idenreplacedy])
				{
					string real = int.Parse(idenreplacedy).ToString();
					wzproperty info = package.root["", "info"];
					wzproperty commodity = commodities[real];

					accessory.Add(idenreplacedy, new res_object(
						idenreplacedy.Substring(0, 4),
						idenreplacedy,
						query_name(real, idenreplacedies),
						query_level(info, commodity),
						query_gender(commodity),
						query_cash(info),
						query_job(info),
						""));

					generate_image(location, idenreplacedy, info["iconRaw"]);
				}
			}

			Invoke(new Action<int>(delegate(int o)
			{
				++archive.Value;
			}), 0);
		}
	}

19 View Source File : MarketDepthPainter.cs
License : Apache License 2.0
Project Creator : AlexWan

void _glreplacedBox_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (_glreplacedBox.InvokeRequired)
                {
                    _glreplacedBox.Invoke(new Action<object, EventArgs>(_glreplacedBox_SelectionChanged), sender, e);
                    return;
                }

                decimal price;
                try
                {
                    if (_glreplacedBox.CurrentCell == null ||
                        _glreplacedBox.Rows.Count == 0 ||
                        _glreplacedBox.Rows[_glreplacedBox.CurrentCell.RowIndex].Cells.Count < 2 ||
                        _glreplacedBox.Rows[_glreplacedBox.CurrentCell.RowIndex].Cells[2].Value == null)
                    {
                        return;
                    }
  
                    price = _glreplacedBox.Rows[_glreplacedBox.CurrentCell.RowIndex].Cells[2].Value.ToString().ToDecimal();
                }
                catch (Exception)
                {
                    return;
                }

                if (price == 0)
                {
                    return;
                }
                if (_hostGlreplaced != null)
                {
                    _lastSelectPrice = price;
                    _textBoxLimitPrice.Text = Convert.ToDouble(_lastSelectPrice).ToString(new CultureInfo("RU-ru"));
                }
            }
            catch (Exception error)
            {
                SendNewLogMessage(error.ToString(), LogMessageType.Error);
            }
        }

19 View Source File : JokeCalculatorClientForm.cs
License : MIT License
Project Creator : azist

private void LogTotal(int opQty, int errQty)
    {
      if (m_lblASyncTotal.InvokeRequired)
      {
        var cb = new Action<int, int>(LogTotal);
        this.Invoke(cb, new object[] {opQty, errQty});
      }
      else
      {
        m_lblASyncTotal.Text = "{0:#,#} ops, {1:#,#} err".Args(opQty, errQty);
      }
    }

19 View Source File : JSEditor.cs
License : MIT License
Project Creator : Autodesk-Forge

private void SetText(string text)
    {
      // InvokeRequired required compares the thread ID of the
      // calling thread to the thread ID of the creating thread.
      // If these threads are different, it returns true.
      if (this.txtConsole.InvokeRequired)
      {
        SetTextCallback d = new SetTextCallback(SetText);
        this.Invoke(d, new object[] { text });
      }
      else
      {
        this.txtConsole.Text = text;
      }
    }

19 View Source File : Log.cs
License : Apache License 2.0
Project Creator : AlexWan

private void PaintMessage(LogMessage messageLog)
        {
            try
            {
                if (_grid.InvokeRequired)
                {
                    _grid.Invoke(new Action<LogMessage>(PaintMessage), messageLog);
                    return;
                }

                if (_messageses == null)
                {
                    _messageses = new List<LogMessage>();
                }

                _messageses.Add(messageLog);

                

                DataGridViewRow row = new DataGridViewRow();
                row.Cells.Add(new DataGridViewTextBoxCell());
                row.Cells[0].Value = messageLog.Time;

                row.Cells.Add(new DataGridViewTextBoxCell());
                row.Cells[1].Value = messageLog.Type;

                row.Cells.Add(new DataGridViewTextBoxCell());
                row.Cells[2].Value = messageLog.Message;
                _grid.Rows.Insert(0, row);

            }
            catch (Exception)
            {
                // ignore
            }
        }

19 View Source File : ControlExtensions.cs
License : MIT License
Project Creator : bartekmotyl

public static void InvokeIfRequired<T>(this Control control, Action<T> action, T parameter)
        {
            try
            { 
                if (!control.IsDisposed && control.InvokeRequired)
                    control.Invoke(action, parameter);
                else
                    action(parameter);
                }
            catch (ObjectDisposedException)
            {
            }
        }

19 View Source File : Controlpanel.cs
License : MIT License
Project Creator : alexwahl

public void TcpServer_Enabled_Changed(bool enabled)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<bool>(TcpServer_Enabled_Changed), new object[] { enabled });
                return;
            }
            else
            {
                enabled_ = enabled;
                SetDescriptionOfServerState();
            }
        }

19 View Source File : Form1.cs
License : GNU General Public License v3.0
Project Creator : Benjerman

private void ConsoleOutputHandler(object sendingProcess, System.Diagnostics.DataReceivedEventArgs outLine)
        {
            if (!String.IsNullOrEmpty(outLine.Data))
            {
                if (this.InvokeRequired)
                    this.Invoke(fpTextBoxCallback, Environment.NewLine + outLine.Data);
                else
                    fpTextBoxCallback(Environment.NewLine + outLine.Data);
            }
            
        }

19 View Source File : MainForm.cs
License : GNU General Public License v2.0
Project Creator : AmanoTooko

private void Net_Play(object sender, PlayEvent e)
        {
            if (this.InvokeRequired)
            {
                if (e.Mode==0)
                {
                    var n = new remotePlay(NetPlay);
                    this.Invoke(n, e.Time, e.Text);
                }
                else if (e.Mode == 1)
                {
                    var n = new remotePlay(NetStop);
                    this.Invoke(n, e.Time, e.Text);
                }
                else if (e.Mode==2)
                {
                    var n = new updateForm(upform);
                    this.Invoke(n, e.Text);
                }
                
            }
            else
            {
                if (e.Mode == 0)
                {
                    NetPlay(e.Time, e.Text);
                }
                else if (e.Mode == 1)
                {
                    NetStop(e.Time, e.Text);
                }
                
            }
            
        }

19 View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : boonkerz

private void ClientListener_OnClientConnected(object sender, ClientConnectedEventArgs e)
        {
            if (e.PreplacedwordOk)
            {

                if (this.InvokeRequired)
                {
                    ShowFormCallback d = new ShowFormCallback(openForm);
                    this.Invoke(d, new object[] { e.SystemId });
                }
                else
                {
                    RemoteForm rm = new RemoteForm(e.SystemId, this.txtPreplacedword.Text);
                    rm.Name = "Host: " + e.SystemId;
                    rm.setThread(clientThread);
                    rm.Show();
                    rm.Start();
                }

                this.lblStatus.Text = "Preplacedwort Ok Verbunden mit: " + e.SystemId;

            }
            else
            {
                this.lblStatus.Text = "Preplacedwort Falsch Verbindung abgebrochen von: " + e.SystemId;
            }
        }

19 View Source File : ClientKcp.cs
License : MIT License
Project Creator : a11s

private void button_init_Click(object sender, EventArgs e)
        {
            if (client != null)
            {
                client.Close();
            }
            client = new k.KcpClient("Test".ToCharArray().Select(a => (byte)a).ToArray(), 0, "kcppeer".ToCharArray().Select(a => (byte)a).ToArray());
            var arr = textBox_remote.Text.Split(":"[0]);
            remoteipep = new IPEndPoint(IPAddress.Parse(arr[0]), int.Parse(arr[1]));
            client.OnOperationResponse = (buf) =>
                {
                    Console.WriteLine($"{nameof(CheckBigBBuff)}={CheckBigBBuff(buf)} size:{buf.Length} ");
                };
            client.OnConnected = (sid) =>
            {
                this.Invoke(
                    new Action(() =>
                    {
                        this.Text = sid.ToString();
                    })
                    );

            };

            client.Connect(remoteipep, true);
        }

19 View Source File : manager.cs
License : BSD 2-Clause "Simplified" License
Project Creator : chengse66

private void enumerate_characters(wzpackage host, res_character character, res_root res)
	{
		string location = thumbnails + "character\\";

		Directory.CreateDirectory(location);

		foreach (wzpackage package in host)
		{
			if (null == thread)
				break;

			if (package.idenreplacedy.StartsWith("0001"))
			{
				string idenreplacedy = package.idenreplacedy.Substring(0, 8);

				if (!res["character", "", idenreplacedy])
				{
					character.Add(idenreplacedy, new res_object(
						"0001",
						idenreplacedy,
						"",
						"0",
						gender_neutral,
						cash_negative,
						job_neutral,
						"0000" + idenreplacedy.Substring(4)));

					generate_image(location, idenreplacedy, package.root[""]["front", "head"]);
				}

				Invoke(new Action<int>(delegate(int o)
				{
					++archive.Value;
				}), 0);
			}
		}
	}

19 View Source File : Main.cs
License : GNU General Public License v3.0
Project Creator : AndreiFedarets

private void Instance_MessageArrived(object sender, MessageArrivedEventArgs e)
        {
            Invoke(new LisreplacedemAddDelegate(AppendItem), e.LogInfo);
        }

19 View Source File : Main.cs
License : GNU General Public License v3.0
Project Creator : AndreiFedarets

private void ProcessCurrentState()
        {
            if (IsDisposed)
            {
                return;
            }

            if (InvokeRequired)
            {
                Invoke(new EventHandler(Instance_StateChanged), this, EventArgs.Empty);
            }
            else
            {
                progressBar.Visible = ControllerManager.Instance.CurrentState.IsShortProcess;
                statusLabel.Text = ControllerManager.Instance.CurrentState.Message;
                statusStrip.Refresh();

                startButton.Enabled = !ControllerManager.Instance.CurrentState.Running;
                startToolStripMenuItem.Enabled = !ControllerManager.Instance.CurrentState.Running;
                optionsToolStripMenuItem.Enabled = !ControllerManager.Instance.CurrentState.Running;
                applicationTextBox.Enabled = !ControllerManager.Instance.CurrentState.Running;
                browseButton.Enabled = !ControllerManager.Instance.CurrentState.Running;

                stopButton.Enabled = ControllerManager.Instance.CurrentState.Running;
                stopToolStripMenuItem.Enabled = ControllerManager.Instance.CurrentState.Running;

                if (ControllerManager.Instance.CurrentState.ClearResults)
                {
                    listBox.Items.Clear();
                }
            }
        }

19 View Source File : ClientKcp.cs
License : MIT License
Project Creator : a11s

private void button_pingpong_init_Click(object sender, EventArgs e)
        {
            if (client != null)
            {
                client.Close();
            }
            client = new k.KcpClient("Test".ToCharArray().Select(a => (byte)a).ToArray(), 0, "kcppeerflush".ToCharArray().Select(a => (byte)a).ToArray());
            var arr = textBox_remote.Text.Split(":"[0]);
            remoteipep = new IPEndPoint(IPAddress.Parse(arr[0]), int.Parse(arr[1]));
            client.OnOperationResponse = ReqArrival;
            client.OnConnected = (sid) =>
            {
                this.Invoke(
                    new Action(() =>
                    {
                        this.Text = sid.ToString();
                    })
                    );

            };
            withflush = checkBox_withflush.Checked == true;

            client.Connect(remoteipep, false);
        }

19 View Source File : Form1.cs
License : MIT License
Project Creator : ap0405140

private void timer_elapsed(object sender, ElapsedEventArgs e)
        {
            Invoke(new ShowResult(fshowresult), new object[] { dbla });
        }

19 View Source File : MarketDepthPainter.cs
License : Apache License 2.0
Project Creator : AlexWan

public void StartPaint(WindowsFormsHost glreplaced, System.Windows.Controls.TextBox textBoxLimitPrice)
        {
            try
            {
                if (_glreplacedBox == null)
                {
                    return;
                }
                if (_glreplacedBox.InvokeRequired)
                {
                    _glreplacedBox.Invoke(new Action<WindowsFormsHost, System.Windows.Controls.TextBox>(StartPaint), glreplaced, textBoxLimitPrice);
                    return;
                }

                _textBoxLimitPrice = textBoxLimitPrice;
                _textBoxLimitPrice.TextChanged += _textBoxLimitPrice_TextChanged;
                _hostGlreplaced = glreplaced;

                ProcessBidAsk(_bid, _ask);
                _hostGlreplaced.Child = _glreplacedBox;
                _hostGlreplaced.Child.Refresh();

                _textBoxLimitPrice.Text = Convert.ToDouble(_lastSelectPrice).ToString(new CultureInfo("RU-ru"));

                ProcessMarketDepth(_lastMarketDepth);
            }
            catch (Exception error)
            {
                SendNewLogMessage(error.ToString(), LogMessageType.Error);
            }
        }

19 View Source File : FrmConnect.cs
License : Apache License 2.0
Project Creator : azanov

private void Connect(object arg)
        {
            try
            {
                if (Program.ImapClient.Connect())
                    Invoke(new SuccessDelegate(OnConnectSuccessful));
                else
                    Invoke(new FailedDelegate(OnConnectFailed));
            }
            catch (Exception ex)
            {
                Invoke(new FailedDelegate(OnConnectFailed));
            }
        }

19 View Source File : Main.cs
License : MIT License
Project Creator : Autodesk-Forge

private async void PrepareUserData()
        {
            // make sure this code is being executed on the UI thread
            if (btnSignout.InvokeRequired || browser.InvokeRequired)
            {
                PrepareUserDataCallback c = new PrepareUserDataCallback(PrepareUserData);
                this.Invoke(c, null);
                return;
            }

            if (!SessionManager.Hreplacedession || !(await SessionManager.IsSessionValid())) return;
            
            // empty
            browser.Load(Forge.EndPoints.BaseURL);

            btnSignout.Visible = true;

            // show user name
            Forge.User user = await Forge.User.UserNameAsync();
            lblUserName.Text = string.Format("{0} {1}", user.FirstName, user.LastName);

            // show hubs tree
            TreeNode[] hubs = await Forge.DataManagement.GetHubs();
            treeDataManagement.Nodes.AddRange(hubs);
        }

19 View Source File : SecuritiesUi.xaml.cs
License : Apache License 2.0
Project Creator : AlexWan

private void PaintSecurities(List<Security> securities)
        {
            if(securities == null)
            {
                return;
            }

            if (_grid.InvokeRequired)
            {
                _grid.Invoke(new Action<List<Security>>(PaintSecurities), securities);
                return;
            }

            bool isInArray;
            for (int indexSecuriti = 0; indexSecuriti < securities.Count; indexSecuriti++)
            {
                isInArray = false;

                for (int i = 0; i < _grid.Rows.Count; i++)
                {
                    if (_grid.Rows[i].Cells[0].Value.ToString() == securities[indexSecuriti].Name)
                    {
                        isInArray = true;
                        break;
                    }
                }

                if (isInArray)
                {
                    continue;
                }

                DataGridViewRow nRow = new DataGridViewRow();

                nRow.Cells.Add(new DataGridViewTextBoxCell());
                nRow.Cells[0].Value = securities[indexSecuriti].Name;

                nRow.Cells.Add(new DataGridViewTextBoxCell());
                nRow.Cells[1].Value = securities[indexSecuriti].SecurityType;

                nRow.Cells.Add(new DataGridViewTextBoxCell());
                nRow.Cells[2].Value = securities[indexSecuriti].Lot;

                nRow.Cells.Add(new DataGridViewTextBoxCell());
                nRow.Cells[3].Value = securities[indexSecuriti].PriceStep;

                nRow.Cells.Add(new DataGridViewTextBoxCell());
                nRow.Cells[3].Value = securities[indexSecuriti].PriceStepCost;

                _grid.Rows.Add(nRow);

            }
        }

19 View Source File : JokeCalculatorClientForm.cs
License : MIT License
Project Creator : azist

private void LogLine(string line)
    {
      if (this.m_txtLog.InvokeRequired)
      {
        var cb = new Action<string>(LogLine);
        this.Invoke(cb, new object[] { line});
      }
      else
      {
        m_txtLog.AppendText(line);
        m_txtLog.AppendText(Environment.NewLine);
      }
    }

19 View Source File : ClientUdp.cs
License : MIT License
Project Creator : a11s

private void button_init_Click(object sender, EventArgs e)
        {
            if (client != null)
            {
                client.Close();
            }
            client = new k.UdpClient("Test".ToCharArray().Select(a => (byte)a).ToArray(), 0, "udppeer".ToCharArray().Select(a => (byte)a).ToArray());

            var arr = textBox_remote.Text.Split(":"[0]);
            remoteipep = new IPEndPoint(IPAddress.Parse(arr[0]), int.Parse(arr[1]));
            client.OnOperationResponse = (buf) =>
            {
                var i = BitConverter.ToInt64(buf, 0);
                //Console.Write($"rec:{i}");
                Task.Run(() =>
                {
                    var snd = i + 1;
                    Console.WriteLine($"udp snd:{snd}");
                    client.SendOperationRequest(BitConverter.GetBytes(snd));
                }
                        );
            };
            client.OnConnected = (sid) =>
            {
                this.Invoke(
                    new Action(() =>
                    {
                        this.Text = sid.ToString();
                    })
                    );
            };

            client.Connect(remoteipep, true);
        }

19 View Source File : WaveForm.cs
License : MIT License
Project Creator : azist

private void LogMsg(string msg, bool start = false)
    {
      if (tbLog.InvokeRequired)
      {
        var cb = new Action<string, bool>(LogMsg);
        this.Invoke(cb, msg, start);
      }
      else
      {
        if (!start)
        {
          tbLog.Text += msg + Environment.NewLine;
          tbLog.SelectionStart = tbLog.Text.Length;
        }
        else
        {
          tbLog.Text = msg + Environment.NewLine + Environment.NewLine + tbLog.Text;
          tbLog.SelectionStart = 0;
        }
        tbLog.ScrollToCaret();
      }
    }

19 View Source File : GlobalPosition.cs
License : Apache License 2.0
Project Creator : AlexWan

[System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptionsAttribute]
        public void journal_PositionChangeEvent(Position position)
        {
            if (_startProgram != StartProgram.IsTester)
            {
                return;
            }

            try
            {
                if (_grid.InvokeRequired)
                {
                    _grid.Invoke(new Action<Position>(journal_PositionChangeEvent), position);
                    return;
                }

                if (position.State != PositionStateType.Open && position.State != PositionStateType.Opening &&
                    position.State != PositionStateType.Closing && position.State != PositionStateType.ClosingFail)
                {
                    for (int i = 0; i < _grid.Rows.Count; i++)
                    {
                        if ((int)_grid.Rows[i].Cells[0].Value == position.Number)
                        {
                            _grid.Rows.Remove(_grid.Rows[i]);
                            return;
                        }
                    }
                }
                else
                { 
                    for (int i = 0; i < _grid.Rows.Count; i++)
                    {
                        if ((int)_grid.Rows[i].Cells[0].Value == position.Number)
                        {
                            _grid.Rows.Remove(_grid.Rows[i]);
                            DataGridViewRow row1 = GetRow(position);
                            if (row1 != null)
                            {
                                _grid.Rows.Insert(i, row1);
                            }

                            return;
                        }
                    }
                    DataGridViewRow row = GetRow(position);
                    if (row != null)
                    {
                        _grid.Rows.Add(row);
                    }
                }
            }
            catch (Exception error)
            {
                SendNewLogMessage(error.ToString(), LogMessageType.Error);
            }
        }

19 View Source File : Form1.cs
License : Apache License 2.0
Project Creator : becomequantum

private void LabelText(Label label, string text)
        {
            if (label.InvokeRequired)
            {
                LabelDelegate d = LabelText;
                label.Invoke(d, new object[] { label, text });
            }
            else
            {
                label.Text = text;

            }
        }

19 View Source File : ClientForm1.cs
License : MIT License
Project Creator : a11s

private void button_init_Click(object sender, EventArgs e)
        {
            if (client != null)
            {
                client.Close();
            }
            if (cb_isUdp.Checked)
            {
                client = new k.UdpClient("Test".ToCharArray().Select(a => (byte)a).ToArray(), 0, "udppeer".ToCharArray().Select(a => (byte)a).ToArray());
            }
            else
            {
                if (cb_unreliable.Checked)
                {
                    client = new k.KcpClientEx("Test".ToCharArray().Select(a => (byte)a).ToArray(), 0, "mixpeer".ToCharArray().Select(a => (byte)a).ToArray());
                }
                else
                {
                    client = new k.KcpClient("Test".ToCharArray().Select(a => (byte)a).ToArray(), 0, "kcppeer".ToCharArray().Select(a => (byte)a).ToArray());
                }
            }
            var userid = uint.Parse(textBox_sid.Text);
            var arr = textBox_local.Text.Split(":"[0]);
            localipep = new IPEndPoint(IPAddress.Parse(arr[0]), int.Parse(arr[1]));
            arr = textBox_remote.Text.Split(":"[0]);
            remoteipep = new IPEndPoint(IPAddress.Parse(arr[0]), int.Parse(arr[1]));
            client.OnOperationResponse = (buf) =>
            {
                if (cb_isUdp.Checked)
                {

                    var i = BitConverter.ToInt64(buf, 0);
                    Console.Write($"rec:{i}");
                    Task.Run(() =>
                                {
                                    var snd = i + 1;
                                    Console.WriteLine($"udp snd:{snd}");
                                    client.SendOperationRequest(BitConverter.GetBytes(snd));
                                }
                            );
                }
                else
                {
                    if (cb_unreliable.Checked)//is unreliable
                    {
                        if (buf.Length == sizeof(UInt64))
                        {
                            var i = BitConverter.ToInt64(buf, 0);
                            Console.Write($"rec:{i}");
                            Task.Run(() =>
                            {
                                var snd = i + 1;
                                Console.WriteLine($"unreliable snd:{snd}");
                                clientex?.SendOperationRequest(BitConverter.GetBytes(snd), true);
                            }
                            );
                        }
                        else
                        {
                            //
                            Console.WriteLine($"{nameof(CheckBigBBuff)}={CheckBigBBuff(buf)} size:{buf.Length} reliable");
                        }
                    }
                    else
                    {
                        Console.WriteLine($"{nameof(CheckBigBBuff)}={CheckBigBBuff(buf)} size:{buf.Length} client or clientex.reliable");
                    }
                }
            };
            client.OnConnected = (sid) =>
            {
                this.Invoke(
                    new Action(() =>
                    {
                        this.Text = sid.ToString();
                    })
                    );

            };

            client.Connect(remoteipep, true);
        }

19 View Source File : Form1.cs
License : Apache License 2.0
Project Creator : becomequantum

private void ShowBMP(PictureBox picbox, Image img)
        {
            if (picbox.InvokeRequired)
            {
                ShowBMPDelegate d = ShowBMP;
                picbox.Invoke(d, new object[] { picbox, img });
            }
            else
            {
                picbox.Image = img;
            }
        }

19 View Source File : BotStatus.cs
License : MIT License
Project Creator : altskop

public void update(BehaviorDriver behavior)
        {
            MethodInvoker mi = delegate () {
                isImposterLabel.Text = behavior.botInfo.isImposter.ToString();
                if (behavior.currentStrategy != null)
                modeLabel.Text = behavior.currentStrategy.getMode();
                inEmergencyMeetingLabel.Text = behavior.inEmergencyMeeting.ToString();
            };
            this.Invoke(mi);
        }

19 View Source File : SerialMonitor.cs
License : GNU General Public License v3.0
Project Creator : benlye

private void AppendOutput(string data)
        {
            // Check if we're called from another thread
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string>(this.AppendOutput), new object[] { data });
                return;
            }

            // Use the append method if autoscroll is enabled otherwise just add it
            if (this.checkBoxAutoScroll.Checked)
            {
                this.serialOutput.AppendText(data);
            }
            else
            {
                this.serialOutput.Text += data;
            }
        }

19 View Source File : Controlpanel.cs
License : MIT License
Project Creator : alexwahl

public void TcpServer_Connected_Changed(bool connected)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<bool>(TcpServer_Connected_Changed), new object[] { connected });
                return;
            }
            else
            {
                connected_ = connected;
                SetDescriptionOfServerState();
            }
        }

19 View Source File : FormSplash.cs
License : GNU General Public License v3.0
Project Creator : biheBlockChain

public static void ChangeProgressText(string status)
        {
            ChangeProgressTextDelegate de = new ChangeProgressTextDelegate(ChangeText);
            _splashForm.Invoke(de, status);
        }

19 View Source File : Main.cs
License : GNU Lesser General Public License v3.0
Project Creator : andisturber

public void PrintMessage(string msg)
        {
            if (rtbxLog.InvokeRequired)
            {
                this.Invoke(new Action<string>(PrintMessage), msg);
            }
            else
            {
                rtbxLog.AppendText($"{DateTime.Now.ToString("HH:mm:ss")}:\r\n{msg}\r\n");
            }
        }

19 View Source File : RemoteForm.cs
License : GNU General Public License v3.0
Project Creator : boonkerz

private void Events_OnScreenshotReceived(object sender, Messages.EventArgs.Network.ScreenshotReceivedEventArgs e)
        {
            if (e.Fullscreen)
            {
                Bounds = e.Bounds;
            }

            Ratio = (float)this.drawingArea1.Width / (float)Bounds.Width;

            if (this.drawingArea1.InvokeRequired)
            {
                SetDrawingAreaHeightCallback d = new SetDrawingAreaHeightCallback(setDrawingAreaHeight);
                this.Invoke(d, new object[] { (int)((float)Bounds.Height * Ratio) });
            }
            else
            {
                setDrawingAreaHeight((int)((float)Bounds.Height * Ratio));
            }

            if (e.Nothing)
            {
                return;
            }

            if (e.SystemId == this.SystemId)
            {
                using (var stream = new MemoryStream(e.Image))
                {
                    Image image = Image.FromStream(stream);

                    if (this.drawingArea1.InvokeRequired)
                    {
                        DrawImageCallback d = new DrawImageCallback(drawImage);
                        this.Invoke(d, new object[] { image, e.Bounds });
                    }
                    else
                    {
                        drawImage(image, e.Bounds);
                    }
                    
                }
            }
        }

19 View Source File : GmicConfigDialog.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054

private void ShowErrorMessage(string message)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<string>((string error) => Services.GetService<IExceptionDialogService>().ShowErrorDialog(this, error, string.Empty)),
                       message);
            }
            else
            {
                Services.GetService<IExceptionDialogService>().ShowErrorDialog(this, message, string.Empty);
            }
        }

19 View Source File : manager.cs
License : BSD 2-Clause "Simplified" License
Project Creator : chengse66

private void generate_xml(object parameter)
	{
		res_root res;
		res_group[] groups = parameter as res_group[];

		Invoke(new Action<int>(delegate(int o)
		{ 
			locations.Enabled = false;

			archive.Style = ProgressBarStyle.Marquee;
			total.Style = ProgressBarStyle.Marquee;

			button.Text = "x";
		}), 0);

		res = new res_root();

		foreach (res_group group in groups)
		{
			if (!res.characters.ContainsKey(group.location))
				res.characters.Add(group.location, new res_character(group.location));
			if (!res.items.ContainsKey(group.location))
				res.items.Add(group.location, new res_item(group.location));
		}

		Invoke(new Action<int>(delegate(int o)
		{
			archive.Style = ProgressBarStyle.Blocks;
			total.Style = ProgressBarStyle.Blocks;

			total.Maximum = groups.Length;
		}), 0);

		Directory.CreateDirectory(thumbnails);

		foreach (res_group group in groups)
			if (null != thread)
			{
				res_character character;
				res_item item;
				res_commodity commodities;
				wzproperty idenreplacedies;

				Invoke(new Action<int>(delegate(int o)
				{
					++total.Value;

					archive.Value = 0;

					archive.Maximum = compute_packages_count(group.characters);
					archive.Maximum = archive.Maximum + compute_packages_count(group.items["Install"]);
					archive.Maximum = archive.Maximum + compute_packages_count(group.items["Pet"]);
				}), 0);

				character = res.characters[group.location];
				item = res.items[group.location];
				commodities = new res_commodity(group.commodities);
				idenreplacedies = group.idenreplacedies["Eqp.img"].root["", "Eqp"];
				packages = group.characters;

				while (null != packages.host)
					packages = packages.host;

				enumerate_characters(group.characters, character, res);
				enumerate_accessory(group.characters["Accessory"], idenreplacedies["Accessory"], commodities, character.accessory, res);
				enumerate_cap(group.characters["Cap"], idenreplacedies["Cap"], commodities, character.cap, res);
				enumerate_cape(group.characters["Cape"], idenreplacedies["Cape"], commodities, character.cape, res);
				enumerate_coat(group.characters["Coat"], idenreplacedies["Coat"], commodities, character.coat, res);
				enumerate_face(group.characters["Face"], idenreplacedies["Face"], character.face, res);
				enumerate_glove(group.characters["Glove"], idenreplacedies["Glove"], commodities, character.glove, res);
				enumerate_hair(group.characters["Hair"], idenreplacedies["Hair"], character.hair, res);
				enumerate_longcoat(group.characters["Longcoat"], idenreplacedies["Longcoat"], commodities, character.longcoat, res);
				enumerate_pants(group.characters["Pants"], idenreplacedies["Pants"], commodities, character.pants, res);
				enumerate_petequip(group.characters["PetEquip"], idenreplacedies["PetEquip"], commodities, character.petequip, res);
				enumerate_shield(group.characters["Shield"], idenreplacedies["Shield"], commodities, character.shield, res);
				enumerate_shoes(group.characters["Shoes"], idenreplacedies["Shoes"], commodities, character.shoes, res);
				enumerate_tamingmob(group.characters["TamingMob"], idenreplacedies["Taming"], commodities, character.tamingmob, res);
				enumerate_weapon(group.characters["Weapon"], idenreplacedies["Weapon"], commodities, character.weapon, res);

				enumerate_install(group.items["Install"], group.idenreplacedies["Ins.img"].root[""], item.install, res);
				enumerate_pet(group.items["Pet"], group.idenreplacedies["Pet.img"].root[""], commodities, item.pet, res);
			}
			else
			{
				break;
			}

		res.save();

		foreach (res_group group in groups)
			group.dispose();

		Invoke(new Action<int>(delegate(int o)
		{
			locations.Enabled = true;

			archive.Value = 0;
			total.Value = 0;

			button.Text = "o";
		}), 0);
	}

19 View Source File : FormGUI.cs
License : MIT License
Project Creator : AndnixSH

private bool Init(string il2cppPath, string metadataPath, out Metadata metadata, out Il2Cpp il2Cpp)
        {
            string Mach_O = "2";
            Invoke(new Action(delegate ()
            {
                if (!use64bitMach_O)
                    Mach_O = "1";
            }));

            this.Log("Read config...");
            if (File.Exists(realPath + "config.json"))
            {
                config = JsonConvert.DeserializeObject<Config>(File.ReadAllText(Application.StartupPath + Path.DirectorySeparatorChar + @"config.json"));
            }
            else
            {
                config = new Config();
                Log("config.json file does not exist. Using defaults", Color.Yellow);
            }

            this.Log("Initializing metadata...");
            var metadataBytes = File.ReadAllBytes(metadataPath);
            metadata = new Metadata(new MemoryStream(metadataBytes));
            this.Log($"Metadata Version: {metadata.Version}");
            this.Log("Initializing il2cpp file...");
            var il2cppBytes = File.ReadAllBytes(il2cppPath);
            var il2cppMagic = BitConverter.ToUInt32(il2cppBytes, 0);
            var il2CppMemory = new MemoryStream(il2cppBytes);
            switch (il2cppMagic)
            {
                default:
                    throw new NotSupportedException("ERROR: il2cpp file not supported.");
                case 0x6D736100:
                    var web = new Webreplacedembly(il2CppMemory);
                    il2Cpp = web.CreateMemory();
                    break;
                case 0x304F534E:
                    var nso = new NSO(il2CppMemory);
                    il2Cpp = nso.UnCompress();
                    break;
                case 0x905A4D: //PE
                    il2Cpp = new PE(il2CppMemory);
                    break;
                case 0x464c457f: //ELF
                    if (il2cppBytes[4] == 2) //ELF64
                    {
                        il2Cpp = new Elf64(il2CppMemory);
                    }
                    else
                    {
                        il2Cpp = new Elf(il2CppMemory);
                    }
                    break;
                case 0xCAFEBABE: //FAT Mach-O
                case 0xBEBAFECA:
                    var machofat = new MachoFat(new MemoryStream(il2cppBytes));
                    for (var i = 0; i < machofat.fats.Length; i++)
                    {
                        var fat = machofat.fats[i];
                        //Console.Write(fat.magic == 0xFEEDFACF ? $"{i + 1}.64bit " : $"{i + 1}.32bit ");
                    }
                    var index = int.Parse(Mach_O) - 1;
                    var magic = machofat.fats[index % 2].magic;
                    il2cppBytes = machofat.GetMacho(index % 2);
                    il2CppMemory = new MemoryStream(il2cppBytes);
                    if (magic == 0xFEEDFACF)
                        goto case 0xFEEDFACF;
                    else
                        goto case 0xFEEDFACE;
                case 0xFEEDFACF: // 64bit Mach-O
                    il2Cpp = new Macho64(il2CppMemory);
                    break;
                case 0xFEEDFACE: // 32bit Mach-O
                    il2Cpp = new Macho(il2CppMemory);
                    break;
            }

            var version = config.ForceIl2CppVersion ? config.ForceVersion : metadata.Version;
            il2Cpp.SetProperties(version, metadata.maxMetadataUsages);
            this.Log($"Il2Cpp Version: {il2Cpp.Version}");
            if (il2Cpp.Version >= 27 && il2Cpp is ElfBase elf && elf.IsDumped)
            {
                FormDump form = new FormDump();
                form.dumpNoteLbl.Text = "Input global-metadata.dat dump address:";
                form.Message = 0;
                if (form.ShowDialog() == DialogResult.OK)
                {
                    metadata.Address = Convert.ToUInt64(form.ReturnedText, 16);
                    this.Log("Inputted address: " + metadata.Address.ToString("X"));
                }
            }

            this.Log("Searching...");
            try
            {
                var flag = il2Cpp.PlusSearch(metadata.methodDefs.Count(x => x.methodIndex >= 0), metadata.typeDefs.Length, metadata.imageDefs.Length);
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    if (!flag && il2Cpp is PE)
                    {
                        this.Log("Use custom PE loader");
                        il2Cpp = PELoader.Load(il2cppPath);
                        il2Cpp.SetProperties(version, metadata.maxMetadataUsages);
                        flag = il2Cpp.PlusSearch(metadata.methodDefs.Count(x => x.methodIndex >= 0), metadata.typeDefs.Length, metadata.imageDefs.Length);
                    }
                }
                if (!flag)
                {
                    flag = il2Cpp.Search();
                }
                if (!flag)
                {
                    flag = il2Cpp.SymbolSearch();
                }
                if (!flag)
                {
                    Log("ERROR: Can't use auto mode to process file, input offset pointers to try manual mode.", Color.Yellow);
                    var codeRegistration = Convert.ToUInt64(CodeRegistrationTxtBox.Text, 16);
                    var metadataRegistration = Convert.ToUInt64(metadataRegistrationTxtBox.Text, 16);
                    il2Cpp.Init(codeRegistration, metadataRegistration);
                    return true;
                }
            }
            catch (Exception ex)
            {
                Log("An error occurred while processing.", Color.Orange);
                Log(ex.ToString(), Color.Orange);
                return false;
            }
            return true;
        }

19 View Source File : MarketDepthPainter.cs
License : Apache License 2.0
Project Creator : AlexWan

private void PaintMarketDepth(MarketDepth depth)
        {
            try
            {
                _lastMarketDepth = depth;

                if (_hostGlreplaced == null || depth == null)
                {
                    return;
                }

                if (_glreplacedBox.InvokeRequired)
                {
                    _glreplacedBox.Invoke(new Action<MarketDepth>(PaintMarketDepth), depth);
                    return;
                }

                if (depth.Bids[0].Bid == 0 ||
                    depth.Asks[0].Ask == 0)
                {
                    return;
                }

                decimal maxVol = 0;

                decimal allBid = 0;

                decimal allAsk = 0;

                for (int i = 0; depth.Bids != null && i < 25; i++)
                {
                    if (i < depth.Bids.Count)
                    {
                        _glreplacedBox.Rows[25 + i].Cells[2].Value = depth.Bids[i].Price.ToStringWithNoEndZero();
                        _glreplacedBox.Rows[25 + i].Cells[3].Value = depth.Bids[i].Bid.ToStringWithNoEndZero();
                        if (depth.Bids[i].Bid > maxVol)
                        {
                            maxVol = depth.Bids[i].Bid;
                        }
                        allAsk += depth.Bids[i].Bid;
                    }
                    else if (_glreplacedBox.Rows[25 + i].Cells[2].Value != null)
                    {
                        _glreplacedBox.Rows[25 + i].Cells[0].Value = null;
                        _glreplacedBox.Rows[25 + i].Cells[1].Value = null;
                        _glreplacedBox.Rows[25 + i].Cells[2].Value = null;
                        _glreplacedBox.Rows[25 + i].Cells[3].Value = null;
                    }
                }


                for (int i = 0; depth.Asks != null && i < 25; i++)
                {
                    if (i < depth.Asks.Count)
                    {
                        _glreplacedBox.Rows[24 - i].Cells[2].Value = depth.Asks[i].Price.ToStringWithNoEndZero();
                        _glreplacedBox.Rows[24 - i].Cells[3].Value = depth.Asks[i].Ask.ToStringWithNoEndZero();

                        if (depth.Asks[i].Ask > maxVol)
                        {
                            maxVol = depth.Asks[i].Ask;
                        }

                        allBid += depth.Asks[i].Ask;
                    }
                    else if (_glreplacedBox.Rows[24 - i].Cells[2].Value != null)
                    {
                        _glreplacedBox.Rows[24 - i].Cells[2].Value = null;
                        _glreplacedBox.Rows[24 - i].Cells[3].Value = null;
                        _glreplacedBox.Rows[24 - i].Cells[0].Value = null;
                        _glreplacedBox.Rows[24 - i].Cells[1].Value = null;
                    }

                }
                // volume in sticks for ask
                // объём в палках для аска
                for (int i = 0; depth.Bids != null && i < 25 && i < depth.Bids.Count; i++)
                {
                    int percentFromMax = Convert.ToInt32(depth.Bids[i].Bid / maxVol * 50);

                    if (percentFromMax == 0)
                    {
                        percentFromMax = 1;
                    }

                    StringBuilder builder = new StringBuilder(percentFromMax);
                    for (int i2 = 0; i2 < percentFromMax; i2++)
                    {
                        builder.Append('|');
                    }

                    _glreplacedBox.Rows[25 + i].Cells[1].Value = builder;

                }
                // volume in bid sticks
                // объём в палках для бида
                for (int i = 0; depth.Asks != null && i < 25 && i < depth.Asks.Count; i++)
                {
                    int percentFromMax = Convert.ToInt32(depth.Asks[i].Ask / maxVol * 50);

                    if (percentFromMax == 0)
                    {
                        percentFromMax = 1;
                    }

                    StringBuilder builder = new StringBuilder(percentFromMax);

                    for (int i2 = 0; i2 < percentFromMax ; i2++)
                    {
                        builder.Append('|');
                    }

                    _glreplacedBox.Rows[24 - i].Cells[1].Value = builder;
                }

                decimal maxSeries;

                if (allAsk > allBid)
                {
                    maxSeries = allAsk;
                }
                else
                {
                    maxSeries = allBid;
                }
                // volume replacedulative for ask
                // объём комулятивный для аска
                decimal summ = 0;
                for (int i = 0; depth.Bids != null && i < 25 && i < depth.Bids.Count; i++)
                {
                    summ += depth.Bids[i].Bid;

                    int percentFromMax = Convert.ToInt32(summ / maxSeries * 50);

                    if (percentFromMax == 0)
                    {
                        percentFromMax = 1;
                    }

                    StringBuilder builder = new StringBuilder(percentFromMax);
                    for (int i2 = 0; i2 < percentFromMax; i2++)
                    {
                        builder.Append('|');
                    }

                    _glreplacedBox.Rows[25 + i].Cells[0].Value = builder;

                }
                // volume is replacedulative for bids
                // объём комулятивный для бида
                summ = 0;
                for (int i = 0; depth.Asks != null && i < 25 && i < depth.Asks.Count; i++)
                {
                    summ += depth.Asks[i].Ask;

                    int percentFromMax = Convert.ToInt32(summ / maxSeries * 50);

                    if (percentFromMax == 0)
                    {
                        percentFromMax = 1;
                    }

                    StringBuilder builder = new StringBuilder(percentFromMax);
                    for (int i2 = 0; i2 < percentFromMax; i2++)
                    {
                        builder.Append('|');
                    }

                    _glreplacedBox.Rows[24 - i].Cells[0].Value = builder;

                }
                // _glreplacedBox.Refresh();
            }
            catch (Exception error)
            {
                //SendNewLogMessage(error.ToString(), LogMessageType.Error);
            }
        }

19 View Source File : GmicConfigDialog.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054

private void ShowErrorMessage(Exception exception)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<Exception>((Exception ex) => Services.GetService<IExceptionDialogService>().ShowErrorDialog(this, ex.Message, ex)),
                       exception);
            }
            else
            {
                Services.GetService<IExceptionDialogService>().ShowErrorDialog(this, exception.Message, exception);
            }
        }

19 View Source File : GmicConfigDialog.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054

public override void Send(SendOrPostCallback d, object state)
            {
                dialog?.Invoke(d, state);
            }

19 View Source File : ClientMix.cs
License : MIT License
Project Creator : a11s

private void button_init_Click(object sender, EventArgs e)
        {
            if (client != null)
            {
                client.Close();
            }
            client = new k.KcpClientEx("Test".ToCharArray().Select(a => (byte)a).ToArray(), 0, "mixpeer".ToCharArray().Select(a => (byte)a).ToArray());
            var arr = textBox_remote.Text.Split(":"[0]);
            remoteipep = new IPEndPoint(IPAddress.Parse(arr[0]), int.Parse(arr[1]));
            client.OnOperationResponse = (buf) =>
            {
                if (buf.Length == sizeof(UInt64))
                {
                    var i = BitConverter.ToInt64(buf, 0);
                    Console.WriteLine($"rec unreliable:{i}");
                }
                else
                {
                    Console.WriteLine($"rec reliable {nameof(CheckBigBBuff)}={CheckBigBBuff(buf)} size:{buf.Length} ");
                }
            };
            client.OnConnected = (sid) =>
            {
                this.Invoke(
                    new Action(() =>
                    {
                        this.Text = sid.ToString();
                    })
                    );

            };

            client.Connect(remoteipep, true);
        }

19 View Source File : MarketDepthPainter.cs
License : Apache License 2.0
Project Creator : AlexWan

private void PaintBidAsk(decimal bid, decimal ask)
        {
            try
            {
                if (_hostGlreplaced == null)
                {
                    return;
                }
                if (_glreplacedBox.InvokeRequired)
                {
                    _glreplacedBox.Invoke(new Action<decimal, decimal>(PaintBidAsk), bid, ask);
                    return;
                }

                if (ask != 0 && bid != 0)
                {
                    _glreplacedBox.Rows[25].Cells[2].Value = bid.ToStringWithNoEndZero();
                    _glreplacedBox.Rows[24].Cells[2].Value = ask.ToStringWithNoEndZero();
                }
            }
            catch (Exception error)
            {
                SendNewLogMessage(error.ToString(), LogMessageType.Error);
            }
        }

19 View Source File : FrmConnect.cs
License : Apache License 2.0
Project Creator : azanov

private void Authenticate(object arg)
        {
            try
            {
                if (_authMode == AuthMode.Google)
                {
                    GoogleAccessToken token = GoogleOAuth2Provider.GetAccessToken(_oAuth2Code);
                    GoogleProfile profile = GoogleOAuth2Provider.GetUserProfile(token);

                    Program.ImapClient.Credentials = new OAuth2Credentials(profile.email, token.access_token);
                }
                else if (_authMode == AuthMode.Outlook)
                {
                    var token = OutlookOAuth2Provider.GetAccessToken(_oAuth2Code);
                    var profile = OutlookOAuth2Provider.GetUserProfile(token.access_token);
                    Program.ImapClient.Credentials = new OAuth2Credentials(profile.emails.account, token.access_token);
                }
                else if (_authMode == AuthMode.Yahoo)
                {
                    var token = YahooOAuth2Provider.GetAccessToken(_oAuth2Code);
                    Program.ImapClient.Credentials = new OAuth2Credentials(token.xoauth_yahoo_guid, token.access_token, "ImapX");
                }

                if (Program.ImapClient.Login())
                    Invoke(new SuccessDelegate(OnAuthenticateSuccessful));
                else
                    Invoke(new FailedDelegate(OnAuthenticateFailed));
            }
            catch (Exception ex)
            {
                Invoke(new FailedDelegate(OnAuthenticateFailed), new[] {ex});
            }
        }

See More Examples