问题描述
当我尝试在 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,ref TOOLINFO toolInfo);
解决方法
你要发送什么信息?
解决方案仍然很简单:
public string lpszText;
改为:
public IntPtr lpszText;
然后用 Marshal.PtrToStringAuto()
编组字符串(在 try
/catch
内)
但我在 ToolInfo 的描述中看到您必须分配缓冲区。您可以尝试使用带有预分配长度的 StringBuilder()
:
public StringBuilder lpszText;
然后在发送消息之前
tt.lpszText = new StringBuilder(200);