[Solved] Cross-thread operation not valid: Control ‘Form1’ accessed from a thread other than the thread it was created on

[ad_1]

In this case, write invoke operation inside of method. Then you can access both from control’s thread and other threads.

delegate IntPtr GetWindowHandleDelegate();

private IntPtr GetWindowHandle() {

    if (this.InvokeRequired) {

        return (IntPtr)this.Invoke((GetWindowHandleDelegate)delegate() {

            return GetWindowHandle();

        });
    }

    return this.Handle;
}

or, if you want to avoid delegate hell, you could write in more few code with built-in delegate and lambda.

private IntPtr GetWindowHandle() {
    if (this.InvokeRequired)
        return (IntPtr)this.Invoke((Func<IntPtr>)(GetWindowHandle));

    return this.Handle;
}

0

[ad_2]

solved Cross-thread operation not valid: Control ‘Form1’ accessed from a thread other than the thread it was created on