首页 > 解决方案 > C# 如何在调用 P/Invoke Sendmessage 时捕获 WIN32 0XFFFF 异常

问题描述

当我尝试在 WPF 中使用非托管代码时。例如SendMessage(IntPtr hWnd, int Msg, int wParam, ref TOOLINFO toolInfo),这个函数可能会直接返回TOOLINFO中lpszText的0XFFFF,导致应用程序直接崩溃。我参考了 MSDN,发现这是一个 ERROR_ILLEGAL_CHARACTER 错误。所以我想问:我怎样才能在托管代码中捕捉到这种错误,或者我怎样才能返回 TOOLINFO 一个好的结果。

    struct TOOLINFO
    {
        public int cbSize;
        public int uFlags;
        public IntPtr hwnd;
        public IntPtr uId;
        public RECT rect;
        public IntPtr hinst;
        [MarshalAs(UnmanagedType.LPStr)]
        public string lpszText;
        public IntPtr lParam;
    }
[DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, ref TOOLINFO toolInfo);

标签: c#error-handlingmemory-leakspinvoke

解决方案


你要发送什么信息?

解决方案仍然很简单:

public string lpszText; 

将其更改为:

public IntPtr lpszText; 

然后用Marshal.PtrToStringAuto()(在try/内catch)编组字符串

但是我在ToolInfo的描述中看到您必须分配缓冲区。您可以尝试使用StringBuilder()预先分配的长度:

public StringBuilder lpszText;

然后在发送消息之前

tt.lpszText = new StringBuilder(200);

推荐阅读