gpt4 book ai didi

c# - P/Pnvoke SetFocus 到一个特定的控件

转载 作者:行者123 更新时间:2023-11-30 15:40:13 25 4
gpt4 key购买 nike

是否可以将焦点设置在另一个应用程序的文本框上(使用其类名)。我将窗口句柄作为 IntPtr。但只需要一些关于哪些功能/API 可用于此的指导!

问题是,我使用 SetForegroundWindow API 获取窗口焦点,但它不允许我发送 Ctrl+L 键来聚焦文本框!

任何帮助都会很棒!

最佳答案

...据我所知,这是我必须使用的代码才能完成这项工作——它在我的应用程序和较新的 Windows 等上运行良好。

void SetFocus(IntPtr hwndTarget, string childClassName)
{
// hwndTarget is the other app's main window
// ...
IntPtr targetThreadID = WindowsAPI.GetWindowThreadProcessId(hwndTarget, IntPtr.Zero); //target thread id
IntPtr myThreadID = WindowsAPI.GetCurrentThread(); // calling thread id, our thread id
try
{
bool lRet = WindowsAPI.AttachThreadInput(myThreadID, targetThreadID, -1); // attach current thread id to target window

// if it's not already in the foreground...
lRet = WindowsAPI.BringWindowToTop(hwndTarget);
WindowsAPI.SetForegroundWindow(hwndTarget);

// if you know the child win class name do something like this (enumerate windows using Win API again)...
var hwndChild = EnumAllWindows(hwndTarget, childClassName).FirstOrDefault();

if (hwndChild == IntPtr.Zero)
{
// or use keyboard etc. to focus, i.e. send keys/input...
// SendInput (...);
return;
}

// you can use also the edit control's hwnd or some child window (of target) here
WindowsAPI.SetFocus(hwndChild); // hwndTarget);
}
finally
{
bool lRet = WindowsAPI.AttachThreadInput(myThreadID, targetThreadID, 0); //detach from foreground window
}
}

...所以按照这些思路进行操作(它按正确的顺序执行您需要的操作,不要忘记分离等 - 但您需要根据您的特定条件调整它,控制/编辑 hwnd 等. – 你仍然可能有与目标窗口/应用程序相关的其他问题,这适用于大多数情况,但并非在所有情况下,这是一个很长的故事,正如我所说,取决于你的具体情况),

(WindowsAPI 我相信是典型的 P/Invoke 包装器)基本上你需要附加到另一个线程来进行“输入”操作,我相信这是官方解释“这也允许线程共享它们的输入状态,因此它们可以调用 SetFocus 函数将键盘焦点设置到不同线程的窗口。”谷歌“AttachThreadInput”获取更多信息(了解原因),它也经常与 SetFocus 和其他输入/键盘操作相关联。此外,自动化 API 可以按照建议提供帮助——这是“最干净”的方法——但取决于目标应用程序是否正确公开和处理它——对于大多数应用程序来说仍然“不存在”,不一致等——如果您想处理与那时不同的“自己的应用程序”,您需要问自己什么是最佳方案等。希望这有帮助

注意:必须有十几个类似解决方案的链接(以及 SO),因为这是众所周知的事情,但我找不到正确的链接

该代码是此规范的示例。案例并基于工作代码——但可能需要测试和制定一些细节(这似乎超出了这个问题的范围),例如……
WindowsAPI 持有 Windows API 和 native 调用的 P/Invoke 签名(类似于 MS.Win32.UnsafeNativeMethods)并且它是一个静态类(参见该类或 https://pinvoke.net/ – 也 Accessing Microsoft.Win32.UnsafeNativeMethods? ),应命名为 (Safe/Unsafe)NativeMethods ( https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2015/code-quality/ca1060-move-p-invokes-to-nativemethods-class ) – 另见 IntPtr, SafeHandle and HandleRef - Explained (IntPtr 有点“老”风格)
EnumAllWindows 使用 EnumChildWindowsGetClassName Win API(我猜这是另一个问题)并且需要一个包装方法它很有用(EnumAllWindows 是——它只是通过窗口递归地枚举检查类名)。

关于c# - P/Pnvoke SetFocus 到一个特定的控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9503027/

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