SetWindowPos even when the main thread is blocked?

499 views Asked by At

I'm trying to make my program move itself via a call to SetWindowPos every 10 milliseconds, to follow the cursor. Problem is, when my program's main thread is blocked by a Thread.Sleep(), the window stops moving.

I put the call to SetWindowPos into a secondary System.Thread, but it's still blocked. It appears that SetWindowPos is always handled by the thread that owns the window. So if my main thread is busy, the window can't be moved, even if the request is sent from a different thread.

Is there an alternative way to move a window, even when the thread that owns the window is busy? Thanks!

1

There are 1 answers

0
AudioBubble On

I don't believe so. All UI operations must be performed on the primary application thread which is known as the UI thread in a GUI app. Whether it is a button click event; mouse move; scroll; paint etc including move window, these operations are queued in the applications message queue (sort of like a FIFO buffer that Windows maintains for all apps) which must be processed by the UI thread.

If say a button click event takes a long time becuase the programmer decided to perform a lengthy database operation in the same thread as the callback, then the UI will freeze until the callback is complete which happens to be the database code.

Similarly if somewhere in your UI thread code you have a Thread.Sleep(), then the UI will also freeze during the same period.

Alternatives

You might want to consider moving lengthy operations to another thread or go the easy contempory and recommended way and use async/await. Doing so allows you to perform the lengthy operation without blocking the UI.

Timers

Also, consider using a Timer instead of Thread.Sleep() or equivalent as an alternative to moving the window 100 times a second. Be sure to use the right timer for GUI apps as .NET defines at least four (4) I believe and not all are suitable by default (if at all) for GUI apps.