views:

103

answers:

2

I have a ContextMenuStrip (ctMenuMassEdit) that I want to display when left-clicking a button (btnMassEdit). I want the ContextMenuStrip to be displayed above the button, i.e. position (0,-ContextMenuStrip.Height) relative to the button:

private void btnMassEdit_Click(object sender, EventArgs e)
{
    ctMenuMassEdit.Show(btnMassEdit, new Point(0, -ctMenuMassEdit.Height));
}

However, the Height property is 0 the first time the button is clicked (I assume the ContextMenuStrip isn't created before it is shown the first time), and the result is that the ContextMenuStrip appears on top of the button. The 2nd time I click the button however, it appears in the correct position, so the basic of my logic is at least correct.

I tried adding the following before showing the ContextMenuStrip, but it didn't work as hoped:

if (!ctMenuMassEdit.Created)
{
    ctMenuMassEdit.CreateControl();
}

So, is there a way I can create the ContextMenuStrip before showing it the first time, so I have the correct Height property? I could of course use the hack of showing it, hiding it and showing it again, but that doesn't seem really neat...

A: 

Since nobody else had any suggestions, I can just share what ended to be my solution. It's not really a solution, more a hack, but if I hide it and show it again the first time, it works:

private void btnMassEdit_Click(object sender, EventArgs e)
{
    if (ctMenuMassEdit.Height < 5)
    {
        ctMenuMassEdit.Show(btnMassEdit, new Point(0, -ctMenuMassEdit.Height));
        ctMenuMassEdit.Hide();
    }
    ctMenuMassEdit.Show(btnMassEdit, new Point(0, -ctMenuMassEdit.Height));
}

You might wonder why I check Height < 5 and not simply Height == 0? Well, for some strange reason, the ContextMenuStrip seemed to have a height of 4 before I displayed it the first time (not 0, as one would assume), so it's yet another hack inside the hack ;)

Nailuj
+1  A: 

how about ctMenuMassEdit.Show(btnMassEdit, Me.PointToScreen(btnMassEdit.Location),ToolStripDropDownDirection.AboveRight);

kildare
Thanks, I wasn't aware of the ToolStripDropDownDirection option. Worked like a charm! My final code ended up looking like this:`ctMenuMassEdit.Show(btnMassEdit, new Point(0, 0), ToolStripDropDownDirection.AboveRight);`
Nailuj