I have the following code which works fine in notepad but not in 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);
}
unfortunately the above returns "{Microsoft Word Document}" when selecting a text in WORD or any "richtextbox". How does CTRL+C do it?
NOTE: This works fine in notepad or on any simple text editor.