JayGatsby
JayGatsby

Reputation: 1621

Doing Something When Enter Key Pressed

I'm trying to implement cheat section to my little game. So basically it will be like this:

-User presses enter(or some other button) during the game
-A box opens
-User enters a text
-Cheat activates

Should I add the code inside to form_load function or somewhere else?

I found some codes but they didn't work. For example

if ((Control.ModifierKeys & Keys.Shift) != 0)
            {
                MessageBox.Show("asd");
            }

When I click Shift button nothings happens

Upvotes: 0

Views: 118

Answers (4)

Idle_Mind
Idle_Mind

Reputation: 39122

Override ProcessCmdKey() in your Forms code like this:

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        KeyEventArgs e = new KeyEventArgs(keyData);
        if (e.KeyCode == Keys.Enter)
        {
            MessageBox.Show("asd");
            return true; // optionally suppress further processing of the enter key by other controls on the form
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }

}

This does NOT require KeyPreview to be set to true.

Upvotes: 1

t3chb0t
t3chb0t

Reputation: 18636

Try to set the Form.KeyPreview Property to true:

Gets or sets a value indicating whether the form will receive key events before the event is passed to the control that has focus.

Either in the designer or in the constructor:

public Form1()
{
    InitializeComponent();
    KeyPreview = true;
}

Becasue there is no full answer I present the complete code:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        KeyPreview = true;
        // Full syntax in case you're using some older Visual Studio.
        this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
    }

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if ((Control.ModifierKeys & Keys.Shift) != 0)
        {
            MessageBox.Show("asdf");
        }
    }
}

@Selman22's suggestion won't work without KeyPreview and mine won't of course work without the event handler.

Upvotes: 1

Spiked3
Spiked3

Reputation: 347

Go with the Keyboard class.

You will not need to subscribe to any events, and can use it at any time, although you need to set Focusable=true for certain UI container types, read the help text.

Upvotes: 0

Selman Genç
Selman Genç

Reputation: 101681

You can handle the KeyDown event of your Form:

private void Form_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
      if(e.KeyCode == Keys.Enter)
      {
           // ...        
      }
}

Upvotes: 4

Related Questions