0

I know this is a neverending story ;)

I am new to C# and writing a little tool for working with pictures. I'm trying to catch keystrokes in my tool.

I have done a lot of Google searching, but this is the only code for catching keystroked that works fine for me (more or less).

public partial class HomeUserControl : UserControl
{
    public HomeUserControl(MainForm mainForm)
    {
        mainForm.KeyPreview = true;
        InitializeComponent();
        this.mainForm = mainForm;
        labelVersion.Text = string.Format(Resources.LabelVersion, AppInfo.AppVersion);
    }
// catch Keyboard
    private bool _altModifierPressed = false;
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        _altModifierPressed = (Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt));
        if (_altModifierPressed && Keyboard.IsKeyDown(Key.N))
        {
            buttonNew_Click(this, EventArgs.Empty);
            // Do not send event to focused control by returning true.
            return true;
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }
.....
}

My problem now is: I can't use ALT+N directly after starting the app. I have to minimize/maximize my app or switch to another app and then back to mine. Then it works, but not at firing up the app.

Ah, i forgot: I'm using Visual Studio 19, Windows Forms and Net Framework 4.8.

What did i miss? I hope someone can help me a little.

My english isn't the best but i hope you understand what i try to explain ;)

Greetings Zarrex

eglease
  • 2,445
  • 11
  • 18
  • 28
Zarrex
  • 1
  • 1
    Probably because your control does not yet have focus. Hence the event never reaches it. – fredrik Sep 29 '21 at 15:17
  • Another similar question [here](https://stackoverflow.com/questions/41863914/key-down-event-on-winforms-control-not-firing) (not duplicate as it doesn't have an answer) – Andrew H Sep 29 '21 at 15:29
  • Ok, that can be. But how can i set the focus to the HomeUserControl (which is the mainForm) after starting the app? I haven't found out yet how to do this. – Zarrex Sep 29 '21 at 15:31

0 Answers0