LoginSignup
0
0

More than 1 year has passed since last update.

C# メインスレッドのUIからパラメータを受ける方法他

Last updated at Posted at 2022-09-27

System.Timers.Timerのようにタスク実行する関数の中でFormのUI(例えばTextBox)などを操作するにはInvokeメソッドを使ってdelegateを実行する必要がある。


タイマーが実行される度にTextBox値を1ずつ増やしていく

int counter = 0;

public void CallbackFunc(Object source, ElapsedEventArgs e){
  counter++;
  textbox1.Invoke((MethodInvoker) delegate { 
    textbox1.Text = counter.ToString();
  });
}

逆にTextBoxのTextプロパティの値を受け取りたい場合は、delegateの戻り値を使うのではなく、直接delegateの中で受け取れば良い。

public void CallbackFunc(Object source, ElapsedEventArgs e){
  string txt="";
  textbox1.Invoke((MethodInvoker) delegate { 
    txt = textbox1.Text;
  });
}
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0