I am currently developing a Matrix(layout) Popup Menu using a Form. Inside the popup menu, there's a Button. The button should open a ContextMenuStrip when left clicked, but not right clicked. With that, I didn't assign the ContextMenuStrip to the ContextMenuStrip properties of the button, in the Design panel of the Microsoft Visual Studio. Just for your information, the ContextMenuStrip's location is directly under the Button.
Below are the examples to help you to visualize.
As the title suggests, I can't open the ContextMenuStrip at the first click of the button. It however works on the next clicks. I've tried solution(s) from these links, but to no avail:
Below are the codes involved(all inside of MatrixPopupMenu.cs):
//global variable
private Point contextStripLocation;
//zoomFactorContextStrip -> name of the ContextMenuStrip object
//the button's click event handler
private void button15_Click(object sender, EventArgs e)
{
if((e as MouseEventArgs).Button == MouseButtons.Left)
{
zoomFactorContextStrip.Show(button15, contextStripLocation);
}
}
//matrix popup menu's load event handler
private void MatrixPopupMenu_Load(object sender, EventArgs e)
{
contextStripLocation = new Point(0, this.button15.Height);
}
May I know what can I do to fix this, please?
CodePudding user response:
As I was messing around with the MouseUp and MouseDown event handlers, I somehow managed to fix my own issue.
Simply, I just need two things:
- In the
MouseDownevent handler, theContextMenuStrip.Close()is called. - In the
MouseUpevent handler, theContextMenuStrip.Show()is called.
Below are the codes:
//global variable
private Point contextStripLocation;
//zoomFactorContextStrip -> name of the ContextMenuStrip object
//the button's click event handler
//private void button15_Click(object sender, EventArgs e) -> not used anymore
//instead, replaced with:
//popup menu's mouseup event handler
private void button15_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
this.TopMost = true;
zoomFactorContextStrip.Show(button15, zoomFactorCSLocation);
}
}
//popup menu's mousedown event handler
private void button15_MouseDown(object sender, MouseEventArgs e)
{
zoomFactorContextStrip.Close();
}
//matrix popup menu's load event handler
private void MatrixPopupMenu_Load(object sender, EventArgs e)
{
contextStripLocation = new Point(0, this.button15.Height);
}
To be exact and honest, I don't really know why this works, but it completely solves my issue. It maybe somehow related to Solution 2.


