[英]C# How to catch WIN32 0XFFFF exception when calling P/Invoke Sendmessage
When I try to use unmanaged code in WPF.当我尝试在 WPF 中使用非托管代码时。 eg SendMessage(IntPtr hWnd, int Msg, int wParam, ref TOOLINFO toolInfo), this function may return the 0XFFFF for lpszText in TOOLINFO and application crash directly.
例如 SendMessage(IntPtr hWnd, int Msg, int wParam, ref TOOLINFO toolInfo),这个 function 可能会返回 TOOLINFO 中 lpszText 的 0XFFFF 并且应用程序直接崩溃。 I have referred MSDN and found that it is a ERROR_ILLEGAL_CHARACTER error.
我参考了 MSDN,发现这是一个 ERROR_ILLEGAL_CHARACTER 错误。 So I want to ask: How can I catch this kind of error in managed code, or how can I return TOOLINFO a good result.
所以我想问:我怎样才能在托管代码中捕捉到这种错误,或者我怎样才能返回 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);
What message are you sending?你要发送什么信息?
Still the solution is easy:解决方案仍然很简单:
public string lpszText;
change it to:将其更改为:
public IntPtr lpszText;
and then marshal the string with Marshal.PtrToStringAuto()
(inside a try
/ catch
)然后用
Marshal.PtrToStringAuto()
编组字符串(在try
/ catch
内)
But I see in the description of ToolInfo that YOU have to allocate the buffer.但是我在ToolInfo的描述中看到您必须分配缓冲区。 You could try with a
StringBuilder()
with preallocated length:您可以尝试使用预先分配长度的
StringBuilder()
:
public StringBuilder lpszText;
and then BEFORE sending the message然后在发送消息之前
tt.lpszText = new StringBuilder(200);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.