我不能让PeekMessage工作。实际上,我希望它会让我收到大量的消息,但它的返回值是0。
我使用一个WinForm,启动一个查看消息的后台线程,并在鼠标上使用该窗口。该窗口与以往一样可用,但无法查看任何消息。我做错什么了?最后一个错误一直是0。
[StructLayout(LayoutKind.Sequential)]
public struct NativeMessage
{
public IntPtr handle;
public uint msg;
public IntPtr wParam;
public IntPtr lParam;
public uint time;
public Point p;
public override string ToString()
{
return handle + ", " + msg + ", " + wParam + ", " + lParam + ", " + time + ", " + p;
}
}
[DllImport("user32.dll")]
public static extern int PeekMessage(out NativeMessage lpMsg, IntPtr window, uint wMsgFilterMin, uint wMsgFilterMax, uint wRemoveMsg);
public Form1()
{
ThreadPool.QueueUserWorkItem(o => run());
}
private void run()
{
for (int i = 0; i < 1000000; )
{
NativeMessage a = new NativeMessage();
int c = PeekMessage(out a, IntPtr.Zero, (uint) 0, (uint) 0, (uint) 0);
if (c != 0)
trace(" -> " + c); // prints strings
}
}解决:
Show()来显示我的表单(谢谢你向我展示我所犯的错误)
发布于 2013-08-19 15:17:15
窗口消息队列是每个线程,除非以某种方式相关联(AttachThreadInput,窗口父关系.)
发布于 2013-08-19 15:17:52
当您为NULL参数传递hWnd (即0)时,PeekMessage函数将检索线程消息,并检索属于当前线程的任何窗口的消息。这是在文献资料中显式调用的。
hWnd in,可选的窗口句柄,其消息将被检索。窗口必须属于当前线程。如果hWnd是
NULL,PeekMessage将检索属于当前线程的任何窗口的消息,以及当前线程的消息队列中的任何消息,其hwnd值为NULL(请参见MSG结构)。因此,如果hWnd是NULL,则同时处理窗口消息和线程消息。
由于您是在ThreadPool中的一个新线程上调用此函数,所以它没有要检索的消息。该线程不与任何窗口关联,也没有消息。
当没有可用的消息时,函数返回FALSE (即0)。
如果您是在主UI线程(与表单关联的线程)上调用PeekMessage,则会看到指向窗体窗口的所有消息。
https://stackoverflow.com/questions/18317210
复制相似问题