简体   繁体   中英

C# WinForms how to stop Ding sound in TreeView

If you open any modal dialog inside a keydown event of a TreeView (or in the Form with KeyPreview=true if focus is on a TreeView) you will hear an annoying DING!

How do i prevent it from happening?

This ding usually is a signal that key event wasnt handled (like, by default TextBox will ding for Ctrl+A etc). However, setting e.Handled or e.SuppressKeyPress doesnt help in the case of modal dialog in TreeView. It helps when doing anything EXCEPT opening a modal dialog!

The native Windows treeview control gets very cranky when you pump a message loop in one of its events. The standard solution is to delay the processing of the event until all the events are complete. Easy to do with the Control.BeginInvoke() method. Worked in this case too:

    private void treeView1_KeyDown(object sender, KeyEventArgs e) {
        e.Handled = e.SuppressKeyPress = true;
        this.BeginInvoke(new Action(() => 
            (new Form1()).ShowDialog()
        ));
    }

Capturing keystrokes with ProcessCmdKey worked for me. Override this method of your form:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == (Keys.O | Keys.Control))
    {
        openFileDialog1.ShowDialog();
        return true;
    }

    return base.ProcessCmdKey(ref msg, keyData);
}

Return true to show that keystroke was consumed by form and stop further processing.

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