user32获取异常系统的GetMessage和peek消息.AccessViolationException:试图读写



我是新手。我得到这个例外的最后2天,没有得到解决:(它在vs 2008中运行良好,但当我执行exe文件时,它在一段时间后给出异常

例外是

System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. at clienttesting.EventLoop.GetMessage(MSG& lpMsg, IntPtr hWnd, UInt32 wMsgFil terMin, UInt32 wMsgFilterMax) at clienttesting.EventLoop.Run() in D:nomanwindowsconsolewindowsconsolePr ogram.cs:line 196 at clienttesting.Program.Main() in D:nomanwindowsconsolewindowsconsolePro gram.cs:line 35

代码是

         public static void Run()
    {
        MSG msg = new MSG();
        sbyte ret;
        do
        {
            if ((ret = GetMessage(out msg, IntPtr.Zero, 0, 0)) != -1)
            {
                Thread.Sleep(1000);
                Console.WriteLine("the mesaaeg" + msg.Message.ToString());
                if (msg.Message == WM_QUIT)
                {
                    break;
                }
                if (ret == -1)
                {
                    break; //-1 indicates an error
                }
                else
                {
                    TranslateMessage(ref msg);
                    DispatchMessage(ref msg);
                }
            }
        } while (true);

    }

异常状态

我知道这个问题已经存在很长时间了,但是我在研究同样的错误时登陆了这个页面。我的情况有点不同,但希望这个答案能帮助到一些人。我正在创建一个。net 6控制台应用程序,但我调用相同的Win32 Api方法。

我正在使用PInvoke。Win32 nuget包,这样我就不用手动做所有的DllImports了。

我的错误是在将第一个参数传递给GetMessage方法时,没有使用操作符'&'地址。如果您查看文档,您将看到示例也在msg参数前使用'&'。

我看到您在调用GetMessageTranslateMessageDispatchMessage时使用outref参数修饰符。您试过使用操作符的地址'&'来代替吗?

下面是一个使用新的。net 6控制台模板和PInvoke的相关部分的示例。Win32 nuget包:
using PInvoke;
unsafe
{
    User32.MSG msg;
    while (User32.GetMessage(&msg, IntPtr.Zero, User32.WindowMessage.WM_NULL, User32.WindowMessage.WM_NULL) > 0)   // synchonous call, will block the thread till a message is received
    {
        User32.TranslateMessage(&msg);
        User32.DispatchMessage(&msg);
    }
}

最新更新