tags:

views:

210

answers:

3

The sendkeys code below works well for Notepad but it doesn't work for Calculator. What is the problem? (It's another problem compared to what I sent here http://stackoverflow.com/questions/2604486/c-sendkeys-problem)

[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName,string lpWindowName);
[DllImport("User32")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
private void button1_Click(object sender, EventArgs e)
{
    IntPtr calculatorHandle = FindWindow("SciCalc", "Calculator");
    //IntPtr calculatorHandle = FindWindow("Notepad", "Untitled - Notepad");
    if (calculatorHandle == IntPtr.Zero)
    {
        MessageBox.Show("Calculator is not running.");
        return;
    }
    SetForegroundWindow(calculatorHandle);
    System.Threading.Thread.Sleep(1000);
    SendKeys.SendWait("111*11=");
    //SendKeys.SendWait("{ENTER}");
    //cnt++;
    SendKeys.Flush();
}
+6  A: 

I'll tell you how you can figure out how to send keystorkes to calc.exe.

Use spy++ to monitor the messages on the calc.exe window process as you're using it. To do this go into spy++ and click on the log messages toolbar button. Drag the cursor onto the calc.exe window. The instructions I gave are for VS2008, they may differ slightly for the Spy++ included in other VS versions. But the same functionality has always been available.

You will see exactly what messages are sent as you are entering text. You need to do the same.

Use the Win32 API SendMessage, LPARAM and WPARAM to your found window handle.

Brian R. Bondy
I'll second the use of SendMessage instead of SendKeys. You can find related info here: http://msdn.microsoft.com/en-us/library/ms646280
Morten Mertner
isn't SendKeys just a SendMessage wrapper?
advs89
@Adam: Probably but not sure. I guess my suggestion was that maybe you need to do some other commands in addition to the keys. But whatever it is you can figure it out by watching the messages.
Brian R. Bondy
For anyone finding this thread via Google, I also have a related post here: http://stackoverflow.com/questions/3047375/simulating-key-press-c/3047387#3047387
Brian R. Bondy
A: 

I guess I got the problem. Timing is the problem here. As long as I put sleep() b/w sending command, the calc.exe get it right. It's not a good solution though.

@user203123: Where are you putting the sleep?
Brian R. Bondy
Your posted code (I had to change "SciCalc" to "CalcFrame" since I'm on Win7) worked fine for me. Output was "1221".
advs89
A: 

On Windows 7, you have to do this:

IntPtr calculatorHandle = FindWindow("CalcFrame", "Calculator");
advs89
but based on what you just posted, I'm guessing your problem wasn't in acquiring a window handle
advs89