On Jun 4, 12:56 am, omm...@wp.pl wrote:
I have two RichTextBox controls on a form, and single
ContextMenuStrip
control which serves for both textboxes.
I need to determine which RichTextBox control invokes an event handler
in
ContextMenuStrip.
So I use that code:
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
((RichTextBox)contextMenuStrip.SourceControl).Past e();
}
It works good if I press right mouse button and select paste item,
but if I try Ctrl+V instead of use mouse I get NullReferenceException.
What to do, to make this thing work both for using mouse and keyboard
shortcut?
Regards
This problem has occured since you have specified Ctrl+V as shortcut
key for paste in context menu item. In that case if we press Ctrl + V
the SourceControl for
contextmenu will not be set and will be null. Just check the
condition.
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
if (contextMenuStrip1.SourceControl == null)
{
foreach( Control ctrl in this.Controls)
{
RichTextBox activeBox = ctrl as RichTextBox;
if (activeBox != null && activeBox.ContainsFocus)
activeBox.Paste();
break;
}
return;
}
((RichTextBox)contextMenuStrip1.SourceControl).Pas te();
}
If you don't want to use this type of logic, you can remove the
shortcut key on context menu. Richtextcontrol will auto detect Ctrl+V
combination and paste data from clipboard. If we specify it
explicitly, Ctrl+V for context menu item will be detected.