Reputation: 89
private void richTextBox1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{ //click event
//MessageBox.Show("you got it!");
ContextMenu contextMenu = new System.Windows.Forms.ContextMenu();
MenuItem menuItem = new MenuItem("Cut");
menuItem.Click += new EventHandler(CutAction);
contextMenu.MenuItems.Add(menuItem);
menuItem = new MenuItem("Copy");
menuItem.Click += new EventHandler(CopyAction);
contextMenu.MenuItems.Add(menuItem);
menuItem = new MenuItem("Paste");
menuItem.Click += new EventHandler(PasteAction);
contextMenu.MenuItems.Add(menuItem);
richTextBox1.ContextMenu = contextMenu;
}
}
void CutAction(object sender, EventArgs e)
{
richTextBox1.Cut();
}
void CopyAction(object sender, EventArgs e)
{
Clipboard.SetText(richTextBox1.SelectedText);
}
void PasteAction(object sender, EventArgs e)
{
if (Clipboard.ContainsText())
{
richTextBox1.Text
+= Clipboard.GetText(TextDataFormat.Text).ToString();
}
}
when I mark a text in richTextBox1
and make right mouse button click on the marked text it does nothing only on the second time it's showing the menu.
If I'm not marking any text when running the program and make mouse button right click it will scroll down and will select the last text on the bottom of richTextBox1
.
And another sub question is how can I put the contextmenu
creation code in form load event. So, it will create the contextmenu
only once when running the program and not each time i make right mouse click?
Upvotes: 0
Views: 99
Reputation: 8079
Because on the first click, you add the ContextMenu
and on the second click it is available. This means, when you first right-click the RichTextBox
there is no ContextMenu
attached to it. Move the code to Form_Load or the constructor (Or even better, add the context menu in the designer). MopuseClick events don't need to be handled to show the ContextMenu
:
private void Form1_Load(object sender, EventArgs e)
{
ContextMenu contextMenu = new System.Windows.Forms.ContextMenu();
MenuItem menuItem = new MenuItem("Cut");
menuItem.Click += new EventHandler(CutAction);
contextMenu.MenuItems.Add(menuItem);
menuItem = new MenuItem("Copy");
menuItem.Click += new EventHandler(CopyAction);
contextMenu.MenuItems.Add(menuItem);
menuItem = new MenuItem("Paste");
menuItem.Click += new EventHandler(PasteAction);
contextMenu.MenuItems.Add(menuItem);
richTextBox1.ContextMenu = contextMenu;
}
void CutAction(object sender, EventArgs e)
{
richTextBox1.Cut();
}
void CopyAction(object sender, EventArgs e)
{
Clipboard.SetText(richTextBox1.SelectedText);
}
void PasteAction(object sender, EventArgs e)
{
if (Clipboard.ContainsText())
{
richTextBox1.Text
+= Clipboard.GetText(TextDataFormat.Text).ToString();
}
}
Upvotes: 1