user1678541
user1678541

Reputation:

Capturing keyboard

How can I toggle an event every time F2 is pressed by the user?

if(/*is pressed F2*/){
    this.Close(); 
}

Thanks in advance!

Upvotes: 1

Views: 2215

Answers (4)

user1678541
user1678541

Reputation:

I found the easiest method to do this:

private void preferences_KeyDown( object sender, KeyEventArgs e ) {
    if (e.KeyCode == Keys.F2) {
        this.Close();
    }
}

Upvotes: 0

Hamed
Hamed

Reputation: 2168

First create a key down event like :

    private void form1_KeyDown(object sender, KeyEventArgs e)
    {
        if ( e.KeyCode == Keys.F2 ) 
            this.Close();
    }

And for getting keys when you press the key on the controls of form1 : change form1's KeyPreview to true on form1's page_load event

    private void form1_Load(object sender, EventArgs e)
    {
        this.KeyPreview = true;
    }

Upvotes: 1

user1678541
user1678541

Reputation:

Now this is working with the focus both on the form and other elements in it (now, please mark it as answer if you agreee with me):

public partial class preferences : Form {
    public preferences() {
        InitializeComponent();
        this.KeyPreview = true;
    }
    private void preferences_KeyDown( object sender, KeyEventArgs e ) {
        if (e.KeyCode == Keys.F2) {
            this.Close();
        }
    }
}

Upvotes: 0

sloth
sloth

Reputation: 101142

An easy way is to use a MessageFilter

Create a class that implements IMessageFilter

public class YourFilter : IMessageFilter
{
    public event EventHandler F2Pressed = delegate { };

    private const Int32 WM_KEYDOWN = 0x0100;

    public bool PreFilterMessage(ref Message m)
    {
        if (m.Msg != WM_KEYDOWN)
            return false;

        if ((Keys)m.WParam==Keys.F2)
            F2Pressed(this, new EventArgs());

        return false;
    }
}

and register it using

var filter = new YourFilter();
Application.AddMessageFilter(filter);
filter.F2Pressed += YourEventHandlerHere;

Upvotes: 1

Related Questions