我想從用戶機器上的打開窗體中抓取選定的文本。目前,我有使用GetFocus
定義爲GetFocus - Win32api幫助
'[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」)] 靜態外部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;
}
}
你不能完全通用。即使您可以通過輸入焦點(無論如何也足夠困難)獲得控件的窗口句柄,該窗口可能是一個自定義窗口,它不會響應標準窗口消息來檢索選擇內容。例如,Word使用自己的自定義控件。你想解決什麼問題? –
用戶當前將在任務欄中的應用程序窗口中手動輸入搜索詞。理想情況下,我們希望儘可能地模擬這一過程,以便如果他們正在閱讀我們的內部pdf科學報告,他們可以突出顯示特定的內部數據項目,並使用我們的系統進行搜索,而無需手動複製和粘貼。 – rik
我不認爲你有很大的機會成功與你目前的做法。我很確定沒有一個通用API來獲取當前選擇。我相信這是因爲每個應用程序都可以以自己的方式實現文本選擇。你可以考慮剪貼板監聽器。 –