views:

1183

answers:

1

I've written a c# program which reproduces keyboard strokes programatically. My idea was to pass these keyboard strokes to another application which may have a textbox set in focus.

So in my program i want the user to select the window to which i must redirect the keyboard strokes to. For that, I want to know a method where i can wait, let user select the window to which keyboard strokes must be sent, and then the user clicks ok on my application to confirm, and then my app knows which is the window i must control by obtaining it's hwnd.

How can i do that?

+1  A: 
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Text;

public class MainClass

    // Declare external functions.
    [DllImport("user32.dll")]
    private static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll")]
    private static extern int GetWindowText(IntPtr hWnd,
                                            StringBuilder text,
                                            int count);

    public static void Main() {
        int chars = 256;
        StringBuilder buff = new StringBuilder(chars);

        // Obtain the handle of the active window.
        IntPtr handle = GetForegroundWindow();

        // Update the controls.
        if (GetWindowText(handle, buff, chars) > 0)
        {
            Console.WriteLine(buff.ToString());
            Console.WriteLine(handle.ToString());
        }
    }
}
Koistya Navin
Two doubts in this:-1) How will it wait for the user to select an active window? Won't it return the console to be always the main window?2)GetWindowText is it a Win32 API call? If so, how is that it can accept a stringbuilder, which is a .NET class.
Anirudh Goel
It's just an example of getting foreground window using user32.dll. The rest part is easy - show to user a message, and start background worker which will monitor which application is on top, if it has been change, do what ever you want with it.
Koistya Navin
Thanks a lot. I'l work on that idea.
Anirudh Goel