WPF中获取鼠标相对于屏幕的位置

              WPF中获取鼠标相对于屏幕的位置
                                   周银辉

WPF编程时,我们经常使用Mouse.GetPosition(IInputElement relativeTo)或MouseEventArgs.GetPosition(IInputElement relativeTo)来获取鼠标相对于某一界面元素的相对位置,这自然也联想到另外的一个问题:如何获取鼠标相对于屏幕的位置。  在WPF文档中找了半天也没找到。
但我们别忘了 System.Windows.Forms.Control类中有一个静态属性System.Windows.Forms.Control.MousePosition,我们可以在WPF中继续使用它,当然这需要你的项目添加 System.Windows.Forms和 System.Drawing名字空间,这多少让人有些别扭,因为玩WPF时总有点不喜欢调用System.Windows.Forms下的东西,喜新厌旧吧。
另外一个方法是平台调用,在VB的文档中可以找到一个API:Declare Function GetCursorPos Lib "user32" Alias "GetCursorPos" (lpPoint As POINTAPI) As Long,我们可以在C#中使用它,代码如下:
None.gif using  System;
None.gif
using  System.Collections.Generic;
None.gif
using  System.Text;
None.gif
using  System.Runtime.InteropServices;
None.gif
None.gif
namespace  Samples
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
class Win32
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        [StructLayout(LayoutKind.Sequential)]
InBlock.gif        
public struct POINT
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
public int X;
InBlock.gif            
public int Y;
InBlock.gif
InBlock.gif            
public POINT(int x, int y)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
this.X = x;
InBlock.gif                
this.Y = y;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif       
InBlock.gif
InBlock.gif        [DllImport(
"user32.dll", CharSet = CharSet.Auto)]
InBlock.gif        
public static extern bool GetCursorPos(out POINT pt);     
InBlock.gif         
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
OK,问题解决了:)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值