Question

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,...)

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top