how to get info from windows (to window forom c#)
im trying to make a background program which gets info from to user for example if i mark i word with my cursor i want to get that info to my form i can i do that please help me
i tried finding the right way maybe tray maybe service could find the silution
best regards
Roei BarPosted Oct 18, 2009, 7:37 AM
t's possible to read the selected text in an edit control (or rich edit control) which currently has the focus in another application using the following code:
using System.Runtime.InteropServices;
// declarations required for Win32 functions
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("kernel32.dll")]
static extern uint GetCurrentThreadId();
[DllImport("user32.dll")]
static extern bool AttachThreadInput(uint idAttach, uint idAttachTo,
bool fAttach);
[DllImport("user32.dll")]
static extern IntPtr GetFocus();
[DllImport("user32.dll")]
static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, StringBuilder lParam);
// second overload of SendMessage
[DllImport("user32.dll")]
static extern int SendMessage(IntPtr hWnd, uint Msg, out int wParam, out int lParam);
const uint WM_GETTEXT = 0x0D;
const uint WM_GETTEXTLENGTH = 0x0E;
const uint EM_GETSEL = 0xB0;
// code needed to get selected text - returns empty string if nothing selected
IntPtr hWnd = GetForegroundWindow();
uint processId;
uint activeThreadId = GetWindowThreadProcessId(hWnd, out processId);
uint currentThreadId = GetCurrentThreadId();
AttachThreadInput(activeThreadId, currentThreadId, true);
IntPtr focusedHandle = GetFocus();
AttachThreadInput(activeThreadId, currentThreadId, false);
int len = SendMessage(focusedHandle, WM_GETTEXTLENGTH, 0, null);
StringBuilder sb = new StringBuilder(len);
int numChars = SendMessage(focusedHandle, WM_GETTEXT, len + 1, sb);
int start, next;
SendMessage(focusedHandle, EM_GETSEL, out start, out next);
string selectedText = sb.ToString().Substring(start, next -start);
In order for this code to work it needs to be within another process which has a running message loop. The idea is to get a handle to the current active application, get the Id of the current thread in that application and then attach it to the current thread in your own application. This then enables us to get a handle to the control which currently has the focus before detaching the threads. It's then easy to get the whole of the text in the control and the limits of the selected text.
To avoid the warning you get that the managed method, AppDomain.GetCurrentThreadId() is obsolete (actually it isn't!), I've used the corresponding Win32 function instead.