I'm creating a window through unmanaged CreateWindowEx
using PInvoke to work as a server in order to dispatch SendMessage
calls from a different process. This should be wrapped in a synchronous function (class registration + window creation), something like this:
public bool Start()
{
if (!Running)
{
var processHandle = Process.GetCurrentProcess().Handle;
var windowClass = new WndClassEx
{
lpszMenuName = null,
hInstance = processHandle,
cbSize = WndClassEx.Size,
lpfnWndProc = WndProc,
lpszClassName = Guid.NewGuid().ToString()
};
// Register the dummy window class
var classAtom = RegisterClassEx(ref windowClass);
// Check whether the class was registered successfully
if (classAtom != 0u)
{
// Create the dummy window
Handle = CreateWindowEx(0x08000000, classAtom, "", 0, -1, -1, -1, -1, IntPtr.Zero, IntPtr.Zero, processHandle, IntPtr.Zero);
Running = Handle != IntPtr.Zero;
// If window has been created
if (Running)
{
// Launch the message loop thread
taskFactory.StartNew(() =>
{
Message message;
while (GetMessage(out message, IntPtr.Zero, 0, 0) != 0)
{
TranslateMessage(ref message);
DispatchMessage(ref message);
}
});
}
}
}
return Running;
}
However, the MSDN states that GetMessage
retrieves a message from the calling thread's message queue, therefore that wouldn't be possible as it's wrapped within a different thread/task. I can't simply move the CreateWindowEx
function call to be within taskFactory.StartNew()
scope.
Any ideas on how to achieve this? Perhaps change from GetMessage
to PeekMessage
maybe (the second might use a lot of the CPU, though)?
REQUIREMENTS:
Start
should be synchronous- A new class should be registered every
Start
call - Message loop should be dispatched within a different thread along
GetMessage