July 14, 2005

Displaying a context (popup) menu at the proper location

I can never find this code when i need it, so i'm reposting it here. My particluar needs were around dynamically creating a context menu on a listview control in the proper location.

from http://www.dotnet247.com/247reference/msgs/5/26434.aspx

Courtesy of Mr. Eric Gunnerson (MSFT)


// right click with treeview doesn't set the selected item. This handler
// does...
private void treeView1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
treeView1.SelectedNode = treeView1.GetNodeAt(e.X, e.Y);
if (treeView1.SelectedNode == null)
{
Console.WriteLine("null");
}

// Convert from tree coordinates to screen coordinates, and then back
// to form coordinates so that the context menu pops up at the right spot...
Point spot = this.PointToClient(treeView1.PointToScreen(new Point (e.X, e.Y)));
this.contextMenu1.Show(this, spot);
}
}