DanMossa
DanMossa

Reputation: 1092

Can't use KeyCode in C#

I'm trying to make it so that when the user pressed the PrintScreen button on their keyboard, a Messagebox appears.

I've looked a lot online and this code seems to be the standard of how to go about doing that.

The issue is, I get an error saying,

System.Windows.Forms.KeyPressEventArgs' does not contain a definition for 'KeyCode' and no extension method 'KeyCode' accepting a first argument of type 'System.Windows.Forms.KeyPressEventArgs' could be found (are you missing a using directive or an assembly reference?)

    private void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyCode == Keys.PrintScreen)
        {
            MessageBox.Show("Test");
        }
    }

Upvotes: 1

Views: 8367

Answers (2)

Jar Yit
Jar Yit

Reputation: 985

You can use

 e.Key == Key.Snapshot

This will work on KeyUp and KeyDown events.

Upvotes: 0

Andrej Kikelj
Andrej Kikelj

Reputation: 800

Instead of using KeyPress, use the KeyDown event. KeyPress event will only fire on printable characters, and PrintScreen is not one of them, so it only exposes the KeyChar property, while KeyDown or KeyUp will expose the KeyCode.

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if(e.KeyCode == Keys.PrintScreen)
    {
        MessageBox.Show("Test");
    }
}

Upvotes: 6

Related Questions