开发者

Make shortcuts appear in multiple menus

开发者 https://www.devze.com 2023-03-25 19:03 出处:网络
I am using a TextBox in a custom UserControl that I am creating. It seems that the default contextmenu doesn\'t show the shortcuts for Cut, Copy, Paste. This is fine, as long as they are just working.

I am using a TextBox in a custom UserControl that I am creating. It seems that the default contextmenu doesn't show the shortcuts for Cut, Copy, Paste. This is fine, as long as they are just working.

But my Form using the UserControl has a MenuStrip that contains these default shortcuts as well. But the Cut, Copy, Paste commands are not working anymore, now that the shortcuts are as开发者_StackOverflowsigned to the MenuStrip.

How can I use shortcuts at multiple positions in my forms? What is the best way to pass a global command like Cut and post it deeper into my UserControl? And is it possible to add the shortcuts to the default contextmenu of the textbox?


A MenuStrip item or ToolStrip item doesn't change the focus when it is clicked or its shortcut keystroke is pressed. Which is the ticket to implementing this functionality, the form's ActiveControl tells you which control has the focus. You just need to check if it is a TextBox. Like this:

    private void copyToolStripMenuItem_Click(object sender, EventArgs e) {
        var box = this.ActiveControl as TextBoxBase;
        if (box != null) box.Copy();
    }

Do the same for the Paste() and Cut() methods. You can further enhance the UI by selectively enabling these menu/toolbar items by subscribing to the Application.Idle event and checking if the ActiveControl is a text box and the text box or clipboard contains any text. Like this:

    public Form1() {
        InitializeComponent();
        Application.Idle += Application_Idle;
    }
    protected override void OnFormClosed(FormClosedEventArgs e) {
        Application.Idle -= Application_Idle;
        base.OnFormClosed(e);
    }

    void Application_Idle(object sender, EventArgs e) {
        var box = this.ActiveControl as TextBoxBase;
        copyToolStripMenuItem.Enabled = box != null && box.Text.Length > 0;
        cutToolStripMenuItem.Enabled = copyToolStripMenuItem.Enabled;
        pasteToolStripMenuItem.Enabled = box != null && Clipboard.ContainsText();
    }


You have to just enabled the property of textbox for the same and it will start responding.

Just verify that myTextBox.ShortcutsEnabled = TRUE;

0

精彩评论

暂无评论...
验证码 换一张
取 消