我正在摆弄 Win32 API 和 Windows 消息传递,试图弄清楚事情是如何工作的,我发现了这个问题非常有帮助 https://stackoverflow.com/questions/523405/how-to-send-text-to-notepad-in-c-win32.
我想改进那里提供的解决方案,以便它附加文本,而不是仅仅通过 WM_SETTEXT 替换记事本中的文本。
我的问题是,如何使用 WM_GETTEXTLENGHT,然后使用 WM_GETTEXT 来获取记事本窗口中的当前文本,以便我可以在使用 WM_SETTEXT 之前向其附加新文本?
使用 WM_XXXTEXT 在 32 位和 64 位机器上都有效吗?如果记事本中有大量文本,建议的获取/设置算法仍然有效还是会占用大量资源?如果是这样,是否有另一种方法可以将文本附加到记事本窗口,而无需先复制其中的所有内容?
谢谢你的帮助!!
UPDATE:
这是我根据 David Heffernan 的帮助和 Google/SO 剪切粘贴得出的代码。由于我是 Win32API 的新手,并且从不同来源复制了许多行,因此我非常感谢所有反馈。
[DllImport("User32.dll", CharSet = CharSet.Auto)]
extern static IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, [In] string lpClassName, [In] string lpWindowName);
[DllImport("User32.dll", EntryPoint = "SendMessage")]
extern static int SendMessageGetTextLength(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
[DllImport("User32.dll")]
public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);
[DllImport("User32.dll")]
public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, int lParam);
const int WM_GETTEXTLENGTH = 0x000E;
const int EM_SETSEL = 0x00B1;
const int EM_REPLACESEL = 0x00C2;
public void testAppendText(string text)
{
Process[] notepads = Process.GetProcessesByName("notepad");
if (notepads.Length == 0) return;
if (notepads[0] != null)
{
IntPtr editBox = FindWindowEx(notepads[0].MainWindowHandle, new IntPtr(0), "Edit", null);
int length = SendMessageGetTextLength(editBox, WM_GETTEXTLENGTH, IntPtr.Zero, IntPtr.Zero);
SendMessage(editBox, EM_SETSEL, length, length);
SendMessage(editBox, EM_REPLACESEL, 1, text);
}
}