get selected text of active window ...


Frank Uray

Hi all

I am having some trouble with select the text of the active
window ... I would like to have the same effect like when you
press Ctrl+c in Windows or just get the selected Text back.

Because I am having a background application and because
I am at this point within the void "KeyUp(object sender, KeyEventArgs e)"
I am unable to use "System.Windows.Forms.SendKeys.Send("^(c)");".

I have tried with the following code,
but my knowledge of win API is not good and I dont see the problem:
It works for example in Notepad, but it does not work when the active
window is WordPad or Word ... ???

Thanks for any help !!
Best regards
Frank Uray

static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

static extern IntPtr GetForegroundWindow();

[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError
= true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint

static extern uint GetCurrentThreadId();

static extern bool AttachThreadInput(uint idAttach, uint idAttachTo,
bool fAttach);

static extern IntPtr GetFocus();

static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam,
StringBuilder lParam);

// second overload of SendMessage
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;

public string GetCurrentSelection()


// Variables
System.IntPtr hWnd = GetForegroundWindow();
uint processId;
uint activeThreadId = GetWindowThreadProcessId(hWnd, out
uint currentThreadId = GetCurrentThreadId();

AttachThreadInput(activeThreadId, currentThreadId, true);

System.IntPtr focusedHandle = GetFocus();

AttachThreadInput(activeThreadId, currentThreadId, false);

int len = SendMessage(focusedHandle, WM_GETTEXTLENGTH, 0,

System.Text.StringBuilder sb = new
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 -

return selectedText;

} // End: try
catch (Exception ex)
{ symmetric.clsMessages.ErrorHandling(ex.Message, ex.Source,
ex.StackTrace); } // End: catch

return "";



Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question