I am trying to find a way to do a thread-safe manipulation for positioning a form. I created a thread to change the position of a form when it is shown and to abort it when it is not shown. This works up until I try to change the position. I tried googling a thread-safe way to change the position of a window but couldn't find anything that worked well enough.
I checked around stack overflow but may not have been searching for the proper thread. I have also searched google with the same issue.
Form1 form;
IntPtr handle = FindWindow(null, WINDOW_NAME);
RECT rect;
Thread posThread;
public FormOverlay(Form1 _form) {
InitializeComponent();
form = _form;
posThread = new Thread(move);
}
private void FormOverlay_Load(object sender, EventArgs e) {
GetWindowRect(handle, out rect);
this.Size = new Size(rect.right - rect.left, rect.bottom - rect.top);
posThread.Start();
}
public struct RECT {
public int left, top, right, bottom;
}
public void move() {
while(form.isChecked()) { // Checkbox in another window
this.Top = rect.top;
this.Left = rect.left;
Thread.Sleep(100);
}
}
I get
System.InvalidOperationException: 'Cross-thread operation not valid: Control 'FormOverlay' accessed from a thread other than the thread it was created on.