gpt4 book ai didi

c# - 尝试在我的程序中查看打开的事件窗口时收到问号

转载 作者:太空宇宙 更新时间:2023-11-03 23:30:34 25 4
gpt4 key购买 nike

我构建了一个软件,可以抓取重量并将其扔到光标所在的打开窗口中。一切顺利——我只有一个问题很烦人当我打开 Word 时收到问号 (?)。然后软件挂起无法正确识别窗口。

当我打开 Word - 我看到 Word? - 例如 123.docx。即使我去掉了问号,软件仍然卡在这种情况下。

我的代码:

    [DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

private string GetActiveWindowTitle()
{
const int nChars = 256;
StringBuilder Buff = new StringBuilder(nChars);
IntPtr handle = GetForegroundWindow();
if (GetWindowText(handle, Buff, nChars) > 0)
{
return Buff.ToString();
}
return null;
}

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

[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);

public void Start(string NAME)
{
MSG = lblMSG.Text.Trim();
IntPtr zero = IntPtr.Zero;
for (int i = 0; (i < 60) && (zero == IntPtr.Zero); i++)
{
Thread.Sleep(500);
zero = FindWindow(null, NAME);
}
if (zero != IntPtr.Zero)
{
.
.
.
}
}

问题是什么?如何解决?

谢谢

最佳答案

默认情况下,字符串和 StringBuilder 在 Windows 上被编码为 Unicode,所以这不是问题。但是,您正在调用 GetWindowText 方法的 ANSI 版本(对于 FindWindow 也是如此)- 这根本行不通。 Windows 尝试将它能做的一切从 unicode 转换为 ANSI,但它不能对当前 ANSI 代码页之外的字符做任何事情。

你需要使用CharSet.Auto:

[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

这将在 unicode 系统上使用 unicode 版本的 GetWindowText (GetWindowTextW),在非 unicode 系统上使用 ANSI 版本。

为了比较,在没有 CharSet.Auto 的情况下,我的 Word 会生成

??? ?? عربي ,عربى‎‎ [Compatibility Mode] - Microsoft Word

有了它,

ščř řč عربي ,عربى‎‎ [Compatibility Mode] - Microsoft Word

我的系统语言环境当前设置为阿拉伯语,因此阿拉伯语即使使用 ANSI GetWindowText 也能正常工作 - 如果我改回捷克语,ščř řč 也能正常工作ANSI,而阿拉伯字母将替换为问号。更改为英语将用问号替换所有,因为英语 ANSI 代码页不支持捷克语和阿拉伯语字母。

关于c# - 尝试在我的程序中查看打开的事件窗口时收到问号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32392967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com