-1

I'm trying to write an application that going to proccess and send him the keystrokes ctrl-a and then ctrl-c that i will have the text content in my clipboard.

I read that the correct api is PostMessage`Sendmeesage`. with the api i success to write into a program (notepad for example). but I didnt success to send keystrokes.

here is my code

    public const uint WM_KEYDOWN = 0x0100;
    public const uint WM_KEYUP = 0x0101;
    const int CTRL = 0x11;
    const int A_Key = 0x41;
    const int C_Key = 0x43;

    static void Main(string[] args)
    {
        IntPtr hWnd = FindWindow(null, "Microsoft Word ");
        hWnd = FindWindowEx(hWnd, null, "Edit", null);
        //PostMessage(hWnd, WM_GETTEXT, 0x11, 0);
        Process[] processes = Process.GetProcessesByName("winword");
        foreach (Process p in processes)
        {

            PostMessage((IntPtr)hWnd, WM_KEYDOWN, (IntPtr)CTRL, 1);
            PostMessage((IntPtr)hWnd, WM_KEYDOWN, (IntPtr)A_Key, 1);
            PostMessage((IntPtr)hWnd, WM_KEYUP, (IntPtr)A_Key, 1);
            PostMessage((IntPtr)hWnd, WM_KEYUP, (IntPtr)CTRL, 1);

                }
            } 

what i'm doing wrong?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • 3
    Microsoft Word does *not* have a client window named "Edit". Use Spy++ to look at the window hierarchy and names. – Hans Passant Jan 06 '13 at 17:32

1 Answers1

0

Perhaps, you are using wrong API to serve the right need. You may observe the sequence of messages being just as you coded up but, posting the messages in that order may not do just as you think it would. If you are determined to solve this way, read <<this post>> and see if a short delay helps. However, I suggest employing a better approach of using SendInput() function which is designed to serve similar scenarios. Check <<this link>> and <<this link>> for more information.

Community
  • 1
  • 1
Bobby
  • 251
  • 1
  • 8
  • well the delay didnt help because i dont want to focus the app. its should work as a backround. and the spy++ shows the same lines at the log for my application and for real pressing ctrl-a ctrl-c. – user1953162 Jan 06 '13 at 18:39
  • As noted above, not all programs process input just by the message ID and order, word is complex input processing application and I am not surprised a delay did not help. Often, calls such as are used that cant' be managed with PostMessage(). SendInput is your best bet, IMO. – Bobby Jan 06 '13 at 18:48