The way I thought it should be done (but it’s wrong):

Point mousePoint = Mouse.GetPosition(this);
MyWindow win = new MyWindow();
win.Left = mousePoint.X;
win.Top = mousePoint.Y;
win.ShowDialog();

“Mama Freeda! Dang window won’t go where I put it!”

Okay, maybe I didn’t say “Mama Freeda” nor “Dang” but none the less it
seems like when getting a mouse position in WPF and trying to open a new
window relative to the mouse click is a pain.

Ah Luigi, but I have the solution 🙂

When setting the left and top properties in a wpf window they relate to
the desktop coordinates. The new window could careless that it’s being
popped up from a control underneath it.

The problem is that Mouse.GetPosition(this) returns the position
relative to the “this” which is most likely the control that is trying
to open the new window. Now if the control is the only control in the
window, there is only one screen, the application is running on the
primary screen and the application is maximized then your golden.

But screw that.

Well, how about using Mouse.GetPosition(Window.GetWindow(this))?

That returns the point relative to the window of the control (this).
That should work won’t it? That only eliminates a single concern of
ours, if the control is the only control in the window. There is still
that the application must be only one screen, the application is running
on the primary screen and the application must be maximized.

Brian, cut the Brother Stuart and just give us the simple answer!

Um, who’s Brother Stuart?

And why am I talking to myself like this?

The great thing about wpf controls is that they have the ability given a
point to convert that point to screen (i.e. desktop) coordinates.

So here is easy answer (The way it should be done):

Point mousePoint = this.PointToScreen(Mouse.GetPosition(this));
MyWindow win = new MyWindow();
win.Left = mousePoint.X;
win.Top = mousePoint.Y;
win.ShowDialog();

Basically get the mouse position relative to this control and then
convert it out to the desktop coordinates so I can then use it when
setting the left and top properties of a new window. This is great for
pop-up windows that need to be close to a mouse click. The great thing
about this is that since the mouse click position is now relative to the
desktop this works on multi-screen monitors regardless of which monitor
you have the application running on.

Later ‘yall,
Brian

ref:
Visual.PointToScreen
http://msdn.microsoft.com/en-us/library/system.windows.media.visual.pointtoscreen.aspx
Mouse.GetPosition
http://msdn.microsoft.com/en-us/library/system.windows.input.mouse.getposition.aspx
Window.Top
http://msdn.microsoft.com/en-us/library/system.windows.window.top.aspx

Leave a Reply

Your email address will not be published. Required fields are marked *

FormatException

928 East Plymouth Drive Asbury Park, NJ 07712