WPF Mouse and Point Acrobatics

來源:互聯網
上載者:User

I was recently working on implementing mouse
gestures in WPF, and was a bit confused with the Point API. To clarify
this, I wanted to give a few quick examples that might help people
currently working with it:

To get a point relative to a UI element:

view source
print
?
1 private
Point GetPointRelativeToElement(UIElement element, Point point)
2 {
3       
return
element.TranslatePoint(point, element);
4 }

To get the absolute screen position of a UI element,

view source
print
?
1 private
Point GetAbsolutePositionOfElement(UIElement element)
2 {
3      
return
element.PointToScreen(
new
Point(0, 0));
4 }


To get the absolute midpoint of a UI element,

view source
print
?
1 private
Point GetAbsoluteMidPointOfElement(FrameworkElement element)
2 {
3             
Point midPoint = element.TranslatePoint(
new
Point(element.Width / 2, element.Height / 2), element);
4             
Point absolute = PointToScreen(midPoint);
5             
return
absolute;
6 }<br>

To get the relative and absolute mouse position,

view source
print
?
1 private
Point GetAbsoluteMousePosition()
2 {
3        
return
PointToScreen(Mouse.GetPosition(
this
));
4 }
5  
6 private
Point GetMousePositionRelativeToElement(UIElement element)
7 {
8        
return
Mouse.GetPosition(element);
9 }

 

To programmatically adjust mouse position,

view source
print
?
1 using
System.Runtime.InteropServices;
2  
3 // … class declaration
4  
5 [DllImport(
"user32.dll"
)]
6 static
extern
bool
SetCursorPos(
int
X,
int
Y);

Now, you can call SetCursorPos(x,y) with absolute coordinates to set the mouse position.
I hope this helps!

 

http://ivolo.mit.edu/post/WPF-Mouse-and-Point-Acrobatics.aspx

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.