获取活动窗口文本(并发送更多文本)
问题描述:
我在C#中创建了一个小工具,它会在按下全局热键时将一些文本添加到活动文本框中,这是一种自动完成功能。我有我的全局热键工作,但现在我不知道如何获取当前文本在活动文本框(如果活动窗口是一个文本框是。)我迄今试过的是使用获取活动窗口文本(并发送更多文本)
一个。 GetForegroundWindow,然后使用该句柄调用GetWindowText。这给了我活动窗口的窗口标题,而不是文本框内容。
湾GetActiveWindow并使用该句柄调用GetWindowText。这根本没有给我任何文字。
这里是我做了什么
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
[ DllImport("user32.dll") ]
static extern int GetForegroundWindow();
[ DllImport("user32.dll") ]
static extern int GetWindowText(int hWnd, StringBuilder text, int count);
[DllImport("user32.dll")]
static extern int GetActiveWindow();
public static void TestA() {
int h = GetForegroundWindow();
StringBuilder b = new StringBuilder();
GetWindowText(h, b, 256);
MessageBox.Show(b.ToString());
}
public static void TestB() {
int h = GetActiveWindow();
StringBuilder b = new StringBuilder();
GetWindowText(h, b, 256);
MessageBox.Show(b.ToString());
}
那么,如何实现这一目标的任何想法的例子吗?
编辑28.01.2009: 所以,我发现如何做到这一点。这是我用的:
using System;
using System.Text;
using System.Runtime.InteropServices;
public class Example
{
[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);
const int WM_SETTEXT = 12;
const int WM_GETTEXT = 13;
public static void Main()
{
//Wait 5 seconds to give us a chance to give focus to some edit window,
//notepad for example
System.Threading.Thread.Sleep(5000);
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);
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();
}
}
关于这个的一些说明。该示例在做任何事情之前等待5秒钟,让您有机会将焦点放在某个编辑窗口。在我的真实应用程序中,我使用热键来触发此事,但这只会混淆此示例。另外,在生产代码中,您应该检查win32调用的返回值,以查看它们是否成功。
答
请检查,甚至EM_REPLACESEL消息可能无法通过不同的工艺工作,你可能需要使用WM_COPYDATA或致电窗口过程作为URL中给出,