【发布时间】:2010-12-23 23:06:59
【问题描述】:
我有以下代码在记事本中可以正常工作,但在 WORD 中却不行!!
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", SetLastError = true)]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("kernel32.dll")]
public static extern uint GetCurrentThreadId();
[DllImport("user32.dll")]
public static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
[DllImport("user32.dll")]
public static extern IntPtr GetFocus();
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, StringBuilder lParam);
// second overload of SendMessage
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, uint Msg, out int wParam, out int lParam);
[DllImport("user32.dll")]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
public const uint WM_GETTEXT = 0x0D;
public const uint WM_GETTEXTLENGTH = 0x0E;
public const uint EM_GETSEL = 0xB0;
IntPtr hWnd = WinUser.GetForegroundWindow();
uint processId;
uint activeThreadId = WinUser.GetWindowThreadProcessId(hWnd, out processId);
uint currentThreadId = WinUser.GetCurrentThreadId();
WinUser.AttachThreadInput(activeThreadId, currentThreadId, true);
IntPtr focusedHandle = WinUser.GetFocus();
WinUser.AttachThreadInput(activeThreadId, currentThreadId, false);
int len = WinUser.SendMessage(focusedHandle, WinUser.WM_GETTEXTLENGTH, 0, null);
StringBuilder sb = new StringBuilder(len);
int numChars = WinUser.SendMessage(focusedHandle, WinUser.WM_GETTEXT, len + 1, sb);
int start, next;
string selectedText = "";
WinUser.SendMessage(focusedHandle, WinUser.EM_GETSEL, out start, out next);
try
{
selectedText = sb.ToString().Substring(start, next - start);
}
不幸的是,当在 WORD 或任何“richtextbox”中选择文本时,上述内容会返回“{Microsoft Word Document}”。 CTRL+C是怎么做到的?
注意:这在记事本或任何简单的文本编辑器中都可以正常工作。
【问题讨论】:
-
你想模拟按键还是复制数据?
-
不,我只想从另一个窗口复制数据。不使用 CTRL+C,而是执行上述操作。
-
我不敢相信有人否决了这个问题,并且有超过 1K 的浏览量!!..
-
我正在寻找模拟“Ctrl-C”的按键有没有办法在 C# 中做到这一点?
标签: c# richtextbox copy-paste