在c#应用程序中使用user32.dll FindWindow时使用utf字符

本文关键字:FindWindow utf 字符 dll user32 应用程序 | 更新日期: 2023-09-27 18:15:06

LS,我正在使用c#应用程序中的FindWindow方法从web浏览器获取窗口句柄

[DllImport("user32.dll")]
public static extern int FindWindow(string lpClassName, string lpWindowName );

当窗口标题不包含utf字符时,它工作得很好,如下所示:

string caption1 = "pinvoke.net: findwindow (user32) - Google Chrome";
int hwnd = FindWindow(null, caption1);

但当窗口标题中存在utf字符时,它会失败

string caption2 = "Słownik języka polskiego - Google Chrome";
int hwnd2 = FindWindow(null, caption2);

例如hwnd==0

你能为我提供任何建议,如何在c#应用程序中处理包含utf-8字符的浏览器窗口吗。提前谢谢。

ps我已经看到关于在c++中使用带有utf的FindWindow的评论,说:"您可以显式使用API的Unicode版本HWND-windowHnd=FindWindowW(NULL,L"扫雷器"(;"但我仍然不知道如何在c#

在c#应用程序中使用user32.dll FindWindow时使用utf字符

中正确地执行它

我自己还没有尝试过,但你应该可以做到:

[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int FindWindow(string lpClassName, string lpWindowName );

根据MSDN关于DllImportAttribute.CharSet字段的文章,默认假设为CharSet.Ansi,这将导致您所描述的行为。