Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending key "hangs" PC in C#

My PC hangs when I send key in Form_Shown() and placing Breakpoint at Form_KeyDown()

 private void Form1_KeyDown(object sender, KeyEventArgs e)
 {           //breakpoint here
        if (e.KeyCode == Keys.A)
        {
            MessageBox.Show("caught");
        }
 }
 private void Form1_Shown(object sender, EventArgs e)
 {
        SendKeys.Send("A");
 }
like image 577
Javed Akram Avatar asked Dec 22 '22 20:12

Javed Akram


1 Answers

I repro, Win7 and VS2008. That looks like a fairly nasty deadlock, you can get out of it by pressing Ctrl+Esc on the keyboard. By default, SendKeys uses a windows hook to inject the keys. Windows hooks can have fairly unpleasant side effects but I wouldn't hesitate to call this a Windows bug.

To fix it, use Project + Add New Item and select the Application Configuration File item template. Make it look like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="SendKeys" value="SendInput"/>
  </appSettings>
</configuration>

If this is really meant to send a keystroke to your form then there are better ways to accomplish that.

like image 169
Hans Passant Avatar answered Jan 08 '23 23:01

Hans Passant