1
votes

I have a windows forms window application. Inside the application we want to open a WPF window that is positioned at a location relative to the mouse position. Let's say, that the window center may be displayed at the mouse coordinates, or another case, that the top left corner of the window may be set as being the mouse coordinates.

I've looked at posts like http://www.formatexception.com/2008/09/wpf-and-mouseposition/ but this does not help me, as I don't have a WPF control open before my window. I only have the windows forms, so the folllowing line is not usable in my case

Point mousePoint = Mouse.GetPosition(this);  
2
The windows forms mouseposition does not help me as it also does not give me the WPF coordinates that I need to put as Top and Left of my window. I think some conversion is missingMarcelo Flores

2 Answers

1
votes

since you have a winforms control available, you can use Control.MousePosition

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.mouseposition.aspx


Are you showing the wpf window from a winforms form? I wrote a quick test that had a Form with a button. When clicking the button it opened a wpf window at the cursor location. This worked fine and i did not create or show any WPF controls before the button click.

I tried with and without setting WindowStartupLocation and they both worked, but it might be worth a try for you to add it. Here's an example:

private void button1_Click(object sender, EventArgs e)
{
  Window w = new Window();
  w.WindowStartupLocation = WindowStartupLocation.Manual;
  w.Left = Control.MousePosition.X;
  w.Top = Control.MousePosition.Y;
  w.Show();
}

Though, if the above code sample doesn't work for you then perhaps you could describe your scenario a little bit further and include some code examples?

0
votes

Building on Bill Tarbell's answer, you may need to account for DPI scaling:

    private Point GetScalingFactor(Window window)
    {
        var zeroPoint = window.PointToScreen(new Point(0, 0));
        var hundredPoint = window.PointToScreen(new Point(100, 100));
        return new Point( 
                    100.0 / (hundredPoint.X - zeroPoint.X), 
                    100.0 / (hundredPoint.Y - zeroPoint.Y));
    }

    private void ShowAtCursor(Window parent, Window toShow)
    {
        var point = parent.PointToScreen(System.Windows.Input.Mouse.GetPosition(parent));
        var scaling = GetScalingFactor(parent);

        toShow.Left = point.X * scaling.X;
        toShow.Top = point.Y * scaling.Y;
        toShow.WindowStartupLocation = WindowStartupLocation.Manual;
        toShow.Show();
    }