Reputation: 228
Goal: A Menustrip with Copy and Paste and the user shall see the Shortcut-Keys.
Problem: If you have a MenuStrip and set the ShortcutKeys the are "catched" by the Menu but no longer by the Textboxes. This means you cannot use Ctrl+C / V in the Textboxes - only by Right-Click. If you remove the Shortcuts the Textboxes work fine.
Why is that? Whats the solution if I dont want to name the Entry "Copy______Ctrl+C"?
Example Project: http://www.file-upload.net/download-4098087/MenuBlocksSTRG.zip.html
MSDN is down ATM i found this links:
Upvotes: 15
Views: 7077
Reputation: 51
Ivan Ičin's solution would become difficult for more complex UIs. But it can be done simpler. Just return false if the focus is on the textbox:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Control | Keys.C) && textBox1.ContainsFocus) return false;
return base.ProcessCmdKey(ref msg, keyData);
}
Also, the copy and paste points in the menubar normally refer to certain controls, let's call it editorControl. So I would rather inverse the test. This way other textboxes can be added to the form without the need to update this function.
With returning false it is also easy to handle Ctrl X and Ctrl V. So in the end I am using this:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (!_editorControl.ContainsFocus && (keyData is (Keys.Control | Keys.C) or (Keys.Control | Keys.V) or (Keys.Control | Keys.X))
{
return false;
}
return base.ProcessCmdKey(ref msg, keyData);
}
Upvotes: 0
Reputation: 21
If it still matters, the simple solution might be: Show only the shortcut keys text, as in the image.
In the TextBox set ShortcutsEnabled to true. That's all!
Upvotes: 2
Reputation: 1
You need something like this?
ToolStripMenuItem Quit = new ToolStripMenuItem();
Quit.Name = "quitToolStripMenuItem";
Quit.Text = "&Quit";
Quit.ShortcutKeys = Keys.Alt | Keys.F4;
Quit.Click += new EventHandler(quitToolStripMenuItem_Click);
Upvotes: 0
Reputation: 9990
This should work for copy, and you can take care of paste in same way:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Control | Keys.C) && textBox1.ContainsFocus)
{
Clipboard.SetText(textBox1.SelectedText);
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
Upvotes: 2
Reputation: 81610
You probably have to handle things yourself in those cases.
Simple example:
private void copyToolStripMenuItem_Click(object sender, EventArgs e) {
if (this.ActiveControl is TextBox) {
Clipboard.SetText(((TextBox)this.ActiveControl).SelectedText);
} else {
// do your menu Edit-Copy code here
}
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e) {
if (this.ActiveControl is TextBox) {
((TextBox)this.ActiveControl).SelectedText = Clipboard.GetText();
} else {
// do you menu Edit-Paste code here
}
}
Upvotes: 1