Get Mouse Position on Canvas (But NOT on window)?

45,205

Solution 1

Doesn't this work?

Point p = Mouse.GetPosition(canvas);

The position of the mouse pointer is calculated relative to the specified element with the upper-left corner of element being the point of origin,

Solution 2

Hi the important thing is the

NOT on the Window

the canvas is part of the window as well. one example:

  • the Window.AllowsTransparency state is on true
  • the Window.Background is #00000000 (completely transparent)
  • the Window.Style is None
  • the Window.State is Maximized and
  • there are NO controls or elements on the window!

... so if you start the application you will see Nothing now tell me how to get the mouseposition on the screen in pixel

!Warning! if you juse Mouse.GetPosition(this); it will return x0 y0 every time

Solution 3

so I solved the Problem by using System.Windows.Forms.Control.MousePosition it's a bit a mix of wpf and Windows.Forms but I've given up xD.

Sorry for yelling :/

To make it easy for me I made a Extension:

<DebuggerHidden> _
<System.Runtime.CompilerServices.Extension> _
Public Function toWfpPoint(p As System.Drawing.Point) As Point
    Return new Point(p.X, p.Y)
End Function

Now I just can juse it like this:

Dim MousPos As Point = System.Windows.Forms.Control.MousePosition.toWfpPoint
Share:
45,205
CodeMouse92
Author by

CodeMouse92

Software Engineer at Canonical Lead Software Engineer at MousePaw Media Author of "Dead Simple Python" (No Starch Press, 2022) You can find many of my articles on DEV! As of 2018, I am largely inactive on StackOverflow due to the anti-social tendencies of the community as a whole, especially the high-reputation members, which results in harassment of beginners and marginalized groups. I largely blame the reputation system and no-accountability downvoting feature.

Updated on November 08, 2020

Comments

  • CodeMouse92
    CodeMouse92 over 3 years

    I have a project in WPF 4 and vb.net 2010.

    I have a canvas inside a window. The window is full screen, but the canvas is set to a solid 640x480 in the center of the window. I need to get the mouse position inside of the canvas, but NOT inside of the window. How do I do this?

  • CodeMouse92
    CodeMouse92 about 13 years
    Hmm. Apparently is does after all, yet trying to use those (set as variables) to set the left and top properties of an object on the same canvas is not working...
  • CodeMouse92
    CodeMouse92 about 13 years
    Found the problem. Solution is in comments of accepted answer on this question:link
  • Marty
    Marty about 8 years
    yeah.. so what do I do if I need that ? in the window.MouseButtonUp event ?