GetFocus - Win32api help
本文关键字:help Win32api GetFocus | 更新日期: 2023-09-27 18:00:57
我正试图从用户机器上打开的表单中获取所选文本。目前我已经尝试使用GetFocus
,它被定义为
'[DllImport("user32.dll")]
static extern int GetFocus();'
在api中,它说-Retrieves the handle to the window that has the keyboard focus, if the window is attached to the calling thread's message queue.
,这解释了为什么我的应用程序可以从应用程序的一部分窗口中获取选定的文本,但不能从外部窗口中获取,例如pdf。
我可以使用哪种替代的win32方法来达到这个目的?
谢谢。
编辑:这是目前的尝试
[DllImport("user32.dll"(]static extern int GetFocus((;
[DllImport("user32.dll")]
static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
[DllImport("kernel32.dll")]
static extern uint GetCurrentThreadId();
[DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(int hWnd, int ProcessId);
[DllImport("user32.dll")]
static extern int GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
static extern int SendMessage(int hWnd, int Msg, int wParam, StringBuilder lParam);
// second overload of SendMessage
[DllImport("user32.dll")]
private static extern int SendMessage(IntPtr hWnd, uint Msg, out int wParam, out int lParam);
const int WM_SETTEXT = 12;
const int WM_GETTEXT = 13;
private static string PerformCopy()
{
try
{
//Wait 5 seconds to give us a chance to give focus to some edit window,
//notepad for example
System.Threading.Thread.Sleep(1000);
StringBuilder builder = new StringBuilder(500);
int foregroundWindowHandle = GetForegroundWindow();
uint remoteThreadId = GetWindowThreadProcessId(foregroundWindowHandle, 0);
uint currentThreadId = GetCurrentThreadId();
//AttachTrheadInput is needed so we can get the handle of a focused window in another app
AttachThreadInput(remoteThreadId, currentThreadId, true);
//Get the handle of a focused window
int focused = GetFocus();
//Now detach since we got the focused handle
AttachThreadInput(remoteThreadId, currentThreadId, false);
//Get the text from the active window into the stringbuilder
SendMessage(focused, WM_GETTEXT, builder.Capacity, builder);
return builder.ToString();
}
catch (System.Exception oException)
{
throw oException;
}
}
检查GetForegroundWindow
。
我认为您目前的方法不太可能成功。我确信并没有一个通用的API来获取当前的选择。我相信这一点,因为每个应用程序都可以用自己的方式实现文本选择。
作为一种替代解决方案,您应该考虑使用剪贴板侦听器。倾听对剪贴板内容的更改,无论何时添加文本,您都可以将其从剪贴板中取出并放入应用程序的窗口中。
我认为这是UI自动化(API屏幕阅读器使用(的工作。这是一篇获得C#中所选文本的帖子。