Sendkeys problem from .NET program

萝らか妹 提交于 2019-12-10 12:13:40

问题


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:


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.




回答2:


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



来源:https://stackoverflow.com/questions/2604486/sendkeys-problem-from-net-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!