gpt4 book ai didi

c# - WinApi - PeekMessage 始终返回 False

转载 作者:太空宇宙 更新时间:2023-11-03 20:13:32 26 4
gpt4 key购买 nike

我无法让 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() 来显示我的表单
  • 并重定向主线程以记录消息
  • (不是 XY 问题,我需要 PeekMessage 才能工作或至少了解如何使用它)

(感谢您指出我犯的错误)

最佳答案

当您为 hWnd 参数传递 NULL(即 0)时,PeekMessage 函数检索线程消息,以及任何窗口的消息属于当前线程。这在 the documentation 中明确指出:

hWnd [in, optional]

A handle to the window whose messages are to be retrieved. The window must belong to the current thread.

If hWnd is NULL, PeekMessage retrieves messages for any window that belongs to the current thread, and any messages on the current thread's message queue whose hwnd value is NULL (see the MSG structure). Therefore if hWnd is NULL, both window messages and thread messages are processed.

由于您是在 ThreadPool 中的新线程上调用此函数,因此没有消息可供它检索。该线程不与任何窗口相关联,也没有消息。

当没有可用消息时,该函数返回 FALSE(即 0)。

如果您在主 UI 线程(与您的表单相关联的线程)上调用 PeekMessage,您将可以查看发往表单窗口的所有消息。

关于c# - WinApi - PeekMessage 始终返回 False,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18317210/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com