0
votes

I am trying to simulate keyboard shortcuts such as (Ctrl + A, Ctrl + Shift + X) into a textbox using the keydown event in a textbox but I have a bit of a dilemma. I am using a listbox to log the events that are thrown when it simulates a keyboard shortcut but it runs the event twice. I ask how would I make it so that it only logs into the listbox the shortcut if it only has a modifier key (ctrl, alt, shift, winkey) + an alphanumeric key (a-z 0-9)?

    private void txtShortcut_KeyDown(object sender, KeyEventArgs e)
    {
        // Example key press: Ctrl + A
        if (e.Shift || e.Control || e.Alt)
        {
            string s = (e.Shift ? Keys.ShiftKey.ToString() + " + " : "") + // Shift
                (e.Control ? Keys.ControlKey.ToString() + " + " : "") +  // Control
                    (e.Alt ? Keys.Menu.ToString() + " + " : "") +  // Alt (menu)
                        e.KeyCode; // Key.

            lbLogger.Items.Add(s);
            // Logger Results:
            // 1) ControlKey + ControlKey
            // 2) ControlKey + A
            // * I'm trying to get it to only post the second line and only log the line
            // when a modifier key + a-z 0-9 key is pressed with it.
        }
    }

What would be the most efficient way to go upon this process of only logging if a modifier key + an a-z or 0-9 key are pressed?

1
You shouldn't simulate the keyboard at all, it's not good practice. Why do you want to?Anton Tykhyy
I'm trying to create a routine that would handle allowing the user to set custom keyboard shortcuts to other methods like menu's and program buttons.Arnold Stephens
By they way, your code looks almost the same as from Mike Power. Same person behind it? stackoverflow.com/questions/676544 stackoverflow.com/questions/676518RvdK

1 Answers

2
votes
private void txtShortcut_KeyDown(object sender, KeyEventArgs e)
    {
                // Example key press: Ctrl + A
        if ((e.Shift || e.Control || e.Alt) && 
            (((e.KeyCode >= Keys.a) && (e.KeyCode <= Keys.z)) ||
            ((e.KeyCode >= Keys.A) && (e.KeyCode <= Keys.Z)) ||
            ((e.KeyCode >= Keys.NumPad0) && (e.KeyCode <= Keys.NumPad9)) ||
            ((e.KeyCode >= Keys.D0) && (e.KeyCode <= Keys.D9))))
        {
            string s = (e.Shift ? Keys.ShiftKey.ToString() + " + " : "") + // Shift
                                (e.Control ? Keys.ControlKey.ToString() + " + " : "") +  // Control
                                        (e.Alt ? Keys.Menu.ToString() + " + " : "") +  // Alt (menu)
                                                e.KeyCode; // Key.

            lbLogger.Items.Add(s);
                        // Logger Results:
                        // 1) ControlKey + ControlKey
                        // 2) ControlKey + A
            // * I'm trying to get it to only post the second line and only log the line
            // when a modifier key + a-z 0-9 key is pressed with it.
        }
    }