以下代码是用来判断当前鼠标是否位于窗口内:
[DllImport("User32.dll")]
public static extern bool PtInRect(ref Rectangle Rects, Point lpPoint);private void dTimer_Tick(object sender, EventArgs e)
{
if (this.WindowState == WindowState.Normal)
{
Point cursorPoint = new Point(); //获取鼠标在屏幕的坐标点
Rectangle Rects = new Rectangle(); //存储当前窗体在屏幕的所在区域
bool prInRect = PtInRect(ref Rects, cursorPoint); //判断鼠标是否位于当前窗体内
if (prInRect)
{
if (this.Top < 0) //窗体的Top属性小于0
this.Top = 0;
else if (this.Left < 0) //窗体的Left属性小于0
this.Left = 0;
}
else
this.Top = 5 - this.Height;
}
在winForm执行正常,但是在WPF中,当鼠标位于窗体范围内时,bool prInRect = PtInRect(ref Rects, cursorPoint)这一句会出现异常,内容如下:
检测到NonCOMVisibleBaseClass
执行了 QueryInterface 调用,请求提供 COM 可见的托管类“System.Windows.Shapes.Rectangle”的类接口。不过,由于该类是从非 COM 可见的类“System.Windows.Shapes.Shape”派生的,QueryInterface 调用将失败。这样做的目的是避免非 COM 可见的基类受 COM 版本规则的约束。请高人指点,问题出在哪,应该怎样解决
[DllImport("User32.dll")]
public static extern bool PtInRect(ref Rectangle Rects, Point lpPoint);private void dTimer_Tick(object sender, EventArgs e)
{
if (this.WindowState == WindowState.Normal)
{
Point cursorPoint = new Point(); //获取鼠标在屏幕的坐标点
Rectangle Rects = new Rectangle(); //存储当前窗体在屏幕的所在区域
bool prInRect = PtInRect(ref Rects, cursorPoint); //判断鼠标是否位于当前窗体内
if (prInRect)
{
if (this.Top < 0) //窗体的Top属性小于0
this.Top = 0;
else if (this.Left < 0) //窗体的Left属性小于0
this.Left = 0;
}
else
this.Top = 5 - this.Height;
}
在winForm执行正常,但是在WPF中,当鼠标位于窗体范围内时,bool prInRect = PtInRect(ref Rects, cursorPoint)这一句会出现异常,内容如下:
检测到NonCOMVisibleBaseClass
执行了 QueryInterface 调用,请求提供 COM 可见的托管类“System.Windows.Shapes.Rectangle”的类接口。不过,由于该类是从非 COM 可见的类“System.Windows.Shapes.Shape”派生的,QueryInterface 调用将失败。这样做的目的是避免非 COM 可见的基类受 COM 版本规则的约束。请高人指点,问题出在哪,应该怎样解决
public static extern bool PtInRect(ref System.Drawing.Rectangle Rects, System.Drawing.Point lpPoint);private void dTimer_Tick(object sender, EventArgs e)
{
if (this.WindowState == WindowState.Normal)
{
System.Drawing.Point cursorPoint = new System.Drawing.Point(); //获取鼠标在屏幕的坐标点
System.Drawing.Rectangle Rects = new System.Drawing.Rectangle(); //存储当前窗体在屏幕的所在区域
bool prInRect = PtInRect(ref Rects, cursorPoint); //判断鼠标是否位于当前窗体内
if (prInRect)
{
if (this.Top < 0) //窗体的Top属性小于0
this.Top = 0;
else if (this.Left < 0) //窗体的Left属性小于0
this.Left = 0;
}
else
this.Top = 5 - this.Height;
}
System.Drawing.Rectangle和Point是一个sturt,你也可以自己定义2个sturt Rect跟Point作为参数传进去试下
public struct Point {
public int x;
public int y;
} public struct Rect {
public int left;
public int top;
public int right;
public int bottom;
}
System.Drawing.Point cursorPoint = new System.Drawing.Point(); System.Drawing.Rectangle Rects = new System.Drawing.Rectangle();
这怎么办?
报啥错?那你别引用了啊。就自己定义2个结构体呗
public struct Point {
public int x;
public int y;
} public struct Rect {
public int left;
public int top;
public int right;
public int bottom;
}
用这2个传进去试下。