tags:

views:

186

answers:

2

THe code below I copied from MSDN with a bit of modification:

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

The problem is the number sequence in Notepad is not continuously. The first click always results 0 (as expected). but from the second click, the result is unpredictable (but the sequence is still in order, e.g. 3, 4, 5, 10, 14, 15, ....)

If I click the button fast enough, I was able to get the result in continuous order (0,1,2,3,4,....) but sometimes it produces more than 2 same numbers (e.g. 0,1,2,3,3,3,4,5,6,6,6,7,8,9,...)

+1  A: 

The first problem happens because SetForegroundWindow can return before the focus was switched, so Sendkeys might run when notepad is not active.

SLaks
+2  A: 

The SetForegroundWindow is not going to wait until the specified window is actually in the foreground. It just "kicks off" the process. So it's quite possible that your SendKeys.SendWait is not sending the key to the window that you expect it to be.

Another issue, not quite related to what you're seeing is that you've got a call to Thread.Sleep in your event handler. That's generally considered to be a bad practise: you shouldn't be blocking your UI thread. It makes your application appear unresponsive.

Dean Harding
The best way to do this, I would think would be on a background thread. Queue the operation to a BackgroundWorker which does the processing on another thread. That way, you can do all the Sleep() and whatever that you need and it never ties up the UI thread. You would just need a little bit of extra logic in your "Click" handler so that it doesn't try to start a new request until the previous one has finished.
Dean Harding
Thank you, .....