简体   繁体   中英

Simulating keyboard shortcuts in textbox_keydown event to handle?

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 (az 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 az or 0-9 key are pressed?

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.
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM