简体   繁体   中英

C# Prevent Hotkeys while TextBox focus

I have a program containing multiple C# Forms TextBoxes. I've set up Hotkeys for the entire form activating certain functions. My problem is that my Hotkeys have been set onto the Form KeyDown event and they activate if I write something on a TextBox.

Example : One Hotkey might be I. Everytime I write the letter onto a textbox the Hotkey activates.

Alterior solutions and problems : I've thought about putting a Key in front of the Hotkey like CTRL+Hotkey, but these also present problems as CTRL+C is Windows Copy command etc. SHIFT is an UpperKey button.

Question : Can I prevent Hotkeys from activating when I am writing onto a TextBox without having to go through all of them in the form?

EDIT: Some code as requested. The button codes come from a stored XML file or the Hotkeys Form+Class (separate) where I've set up a window for them.

    public Hotkeys hotkeysForm = new Hotkeys();

    void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        toggleInformation = hotkeysForm.toggleInformation;

        if (e.Control && e.KeyCode == toggleInformation)
        {
            showInfo(true);
        }
        else if (e.KeyCode == toggleInformation)
        {
            if (!isInfoActive)
                showInfo();
            else
                hideInfo();               
        }

     }

You should try this hack, if it could solve your problem, Create a Extented TextBox and use it in your code. you can handle whether to write the pressed key in textbox or not in hotkeyPressed check.

public class ETextBox : System.Windows.Forms.TextBox
{
    protected override void OnKeyDown(System.Windows.Forms.KeyEventArgs e)
    {
        if (hotKeyPressed) // this is the condition when you don't want to write in text.
        {
            //Do whatever you want to do in this case.
        }
        else
        {
            base.OnKeyDown(e);
        }
    }
}

You can disable hotkeys while texbox is an active control. Add the Enter and Leave events for all textboxes:

    private void textBox_Enter(object sender, EventArgs e)
    {
        KeyPreview = false;
    }

    private void textBox_Leave(object sender, EventArgs e)
    {
        KeyPreview = true;
    }

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