Reputation: 25310
I've noticed something wierd with the WinForm TextBox's Context Menu. The TextBox control has a default context menu that has Cut, Copy, Paste and a few other things. I am trying to replace this menu with one of my own. I have created a simple test application with one form and one text box on the form and added the following code:
Form1()
{
InitailizeComponent();
ContextMenu menu = new ContextMenu();
menu.MenuItems.Add("Hello World", HelloWorld_Clicked);
textBox1.ContextMenu = menu;
}
private void HelloWorld_Clicked(object sender, EventArgs e)
{
MessageBox.Show("Hello World!");
}
When I run this I can get my context menu to appear by right clicking the textbox and then releasing the mouse button without moving the mouse. However if I press the right mouse button over the textbox, hold it down, then move the mouse outside the textbox and finally relase the mouse button then I get the default text box context menu.
Is it possible to stop it doing this?
UPDATE: In case it makes a difference the system is running on Windows XP Pro SP3 & .Net 3.5.
UPDATE 2: I tried this again in .Net Core 6 on Windows 11 with the following code and got the same issue.
namespace WinFormsApp1;
public partial class Form1 : Form
{
public Form1()
{
this.InitializeComponent();
ContextMenuStrip menu = new ContextMenuStrip();
menu.Items.Add("Hello World", null, HelloWorld_Clicked);
textBox1.ContextMenuStrip = menu;
}
private void HelloWorld_Clicked(object? sender, EventArgs e)
{
MessageBox.Show("Hello World!");
}
}
Given MS have now started using GitHub I have raised an issue there.
Upvotes: 3
Views: 957
Reputation: 442
If it helps, I found this answer in another part of the Internet:
[C#] textBox1.ContextMenu = new ContextMenu();
[VB.Net] textBox1.ContextMenu = New ContextMenu()
Upvotes: 0
Reputation: 81610
One thing you can try:
[DllImport("user32.dll")]
public static extern bool ReleaseCapture();
void textBox1_MouseDown(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Right) {
ReleaseCapture();
}
}
Upvotes: 1
Reputation: 56620
I suspect that releasing the mouse button outside the text box opens a context menu for the form instead of the text box. I haven't tested this, it's just a guess. You might be able set a context menu for the form as well with code like this, but I haven't tried it myself:
Form1()
{
InitilizeComponent();
ContextMenu menu = new ContextMenu();
menu.MenuItems.Add("Hello World", HelloWorld_Clicked);
textBox1.ContextMenu = menu;
this.ContextMenu = menu;
}
private void HelloWorld_Clicked(object sender, EventArgs e)
{
MessageBox.Show("Hello World!");
}
Upvotes: 1