c# - 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);
解决方案
你要发送什么信息?
解决方案仍然很简单:
public string lpszText;
将其更改为:
public IntPtr lpszText;
然后用Marshal.PtrToStringAuto()
(在try
/内catch
)编组字符串
但是我在ToolInfo的描述中看到您必须分配缓冲区。您可以尝试使用StringBuilder()
预先分配的长度:
public StringBuilder lpszText;
然后在发送消息之前
tt.lpszText = new StringBuilder(200);
推荐阅读
- python - AttributeError:“str”对象在尝试更新文档时没有属性“items”
- swiftui - SwiftUI NavigationLink isActive 不适用于动态列表
- sql-server - 每年按任命状态返回的员工人数
- c - 为什么这个递归函数不起作用?
- javascript - 在 ReactJS 中为组件添加特定的验证
- c++ - 从nodejs获取c ++中的参数
- yaml - 无法将 EKS 节点组加入 AWS CloudFormation 中的现有 EKScluster
- laravel - 使用 laravel 在 goDaddy 中上传大文件
- android - 如何在没有 GUI 的情况下启动 Android 操作系统,例如没有桌面的 linux?
- google-cloud-bigtable - Google Bigtable 删除时间范围