我正在用c#开发一个通用应用程序,我想要来自任何活动窗口的文本。当用户按下热键时,我的应用程序将使用活动的 Windows 文本数据启动。
它是一个拼写检查应用程序。我的问题是如何从 Microsoft Document 访问文本。我尝试了所有 system32.dll 功能
[DllImport("user32.dll")]
static extern IntPtr GetActiveWindow();
[DllImport("user32.dll")]
public static extern int SendMessage(int hWnd, IntPtr msg,
int wParam, int lParam);
[DllImport("kernel32.dll")]
static extern uint GetCurrentThreadId();
[DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(int hWnd, int ProcessId);
System.Threading.Thread.Sleep(1000);
StringBuilder builder = new StringBuilder(500000);
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);
Console.WriteLine("Text in active window was " + builder);
builder.Append(" Extra text");
//Change the text in the active window
SendMessage(focused, WM_SETTEXT, 0, builder);
//Console.ReadKey();
Console.Read();
但这只会从记事本、浏览器地址栏、写字板等返回文本。但实际上它不适用于 ms office、excel 等微软产品。
我想要任何活动窗口中的文本以进行拼写检查,任何人都可以帮助我吗?
提前感谢。