C# 从另一个应用程序获取文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1873404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:31:38  来源:igfitidea点击:

Get text from another application

c#sendmessage

提问by sventevit

I'd like to retrieve text from textbox in my another application. ProcessName from second application is 'TestTextBox', TextBox's name is 'textBox1'.

我想从另一个应用程序的文本框中检索文本。第二个应用程序的 ProcessName 是“TestTextBox”,TextBox 的名称是“textBox1”。

My code, which returns empty string:

我的代码,返回空字符串:

[DllImport("user32.dll")]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, long wParam, [MarshalAs(UnmanagedType.LPStr)] StringBuilder lParam);

Process[] processes = Process.GetProcessesByName("TestTextBox");
foreach (Process p in processes)
{
    IntPtr pFoundWindow = p.MainWindowHandle;
    const int WM_GETTEXT = 0x0D;
    StringBuilder sb = new StringBuilder();
    IntPtr retVal = SendMessage(pFoundWindow, WM_GETTEXT, 100, sb);
    MessageBox.Show(sb.ToString());
}

采纳答案by Doc Brown

In june there was a discussion of how to find the handle of a child control, perhaps this helps.

六月有一个关于如何找到子控件句柄的讨论,也许这会有所帮助。

回答by Kevin Wienhold

You are getting the WindowHandle of the main Form in the code you posted, according to MSDN a GETTEXT message to a Form should return its title. If you want to get text from a TextBox you should be passing the WindowHandle of the TextBox as the first argument.

您正在发布的代码中获取主表单的 WindowHandle,根据 MSDN,发送到表单的 GETTEXT 消息应返回其标题。如果您想从 TextBox 获取文本,您应该将 TextBox 的 WindowHandle 作为第一个参数传递。

回答by Dour High Arch

What is the "another application"? Is it something you are writing? Could it be running on another machine? In another domain? Under another user account? Could the target application, form, or textbox ever change? Do you need asynchronous (i.e. non-blocking) communication between applications?

什么是“另一个应用程序”?这是你正在写的东西吗?它可以在另一台机器上运行吗?在另一个域?在另一个用户帐户下?目标应用程序、表单或文本框会改变吗?您是否需要应用程序之间的异步(即非阻塞)通信?

If the answer to any of those questions is "yes", you should consider using .Net Remoting. This is available from .Net 2.0.

如果任何这些问题的答案是“是”,您应该考虑使用.Net Remoting。这可以从 .Net 2.0 获得。

回答by Cory Charlton

You could use Windows API like others have mentioned or you could use a library like AutoItthat might make the task a little easier. Not sure what your requirements are.

你可以像其他人提到的那样使用 Windows API,或者你可以使用像AutoIt这样的库,这可能会使任务更容易一些。不确定你的要求是什么。