When to register a method that will call Form.Invoke for an event?

I get the following exception in a windows form application

System.InvalidOperationException: Invoke or BeginInvoke cannot be called in a control until a window handle is created.

The method in which the exception is thrown calls this.Invoke (System.Windows.Forms.Form.Invoke). This method is registered in the event of another class in the constructor, which, apparently, leads to the race condition and this exception.

public Form1() { InitializeComponent(); SomeOtherClass.Instance.MyEvent += new SomeDelegate(MyMethod); } private void MyMethod() { this.Invoke((MethodInvoker)delegate { // ... some code ... } } 

At what stage in the life cycle of a form is Handle created? In which case would it be safe to register a method for a foreign event?

+4
source share
4 answers

Ok, now I changed it to this:

 public Form1(){ InitializeComponent(); } protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); SomeOtherClass.Instance.MyEvent += new SomeDelegate(MyMethod); } private void MyMethod() { this.Invoke((MethodInvoker)delegate { // ... some code ... } } 

alternative version will be

 public Form1(){ InitializeComponent(); SomeOtherClass.Instance.MyEvent += new SomeDelegate(MyMethod); } private void MyMethod() { if (this.IsHandleCreated) { this.Invoke((MethodInvoker)delegate { // ... some code ... } } } 
+2
source

I think that if you register a method in an OnShow event, you should be safe.

+2
source

Place the InitializeComponent () call back before registering the handler as suggested with bitxwise

You will have the same problem if the form is placed so that it can process the handler later.

You can do something like if(this.IsHandleCreated) in your handler to be safe.

+2
source

As already mentioned, IsHandleCreated is the way to go. The following snippet tells how to do this.

 public class TestEvent : Form { protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); MyMethod(); } private void MyMethod() { this.Invoke(new Action(() => { //Here goes your code. })); } } 
0
source

Source: https://habr.com/ru/post/1347696/


All Articles