【发布时间】:2021-06-09 20:46:27
【问题描述】:
我正在通过非托管 CreateWindowEx 创建一个窗口,使用 PInvoke 作为服务器,以便调度来自不同进程的 SendMessage 调用。这应该包含在 同步 函数中(类注册 + 窗口创建),如下所示:
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;
}
但是,MSDN 声明 GetMessage retrieves a message from the calling thread's message queue,因此这是不可能的,因为它被包装在不同的线程/任务中。我不能简单地将CreateWindowEx 函数调用移动到taskFactory.StartNew() 范围内。
关于如何实现这一目标的任何想法?也许从 GetMessage 更改为 PeekMessage 可能(不过,第二个可能会占用大量 CPU)?
要求:
-
Start应该是同步的 - 每个
Start调用都应该注册一个新类 - 消息循环应该沿着
GetMessage在不同的线程中调度
【问题讨论】:
标签: c# winapi sendmessage wndproc