WinForm 求教怎么捕获窗口外的鼠标事件 SetCapture

uddeeqtkg 2012-08-01 06:16:13
我有一个模态对话框想在鼠标点击窗口外的地方时执行一段代码
var form=new Form1();
form.showDialog();

有人说用 SetCapture();

我在form中加了SetCapture(this) 后该怎么做
WndProc(ref Message m) 里还是得不到鼠标的消息

...全文
691 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
大东哥哥的爹 2012-08-26
  • 打赏
  • 举报
回复
写在lostfocus里。
uddeeqtkg 2012-08-02
  • 打赏
  • 举报
回复
遇到一个问题在窗体内部的控件的事件得不到响应了,比如窗体上的 按钮的点击没反应,文本框的不到焦点

protected override void WndProc(ref Message m)
{


if (m.Msg == WM_LBUTTONUP)
{
// ReleaseCapture();
Point p = new Point((int)m.LParam);
if (this.ClientRectangle.Contains(p))
{
base.WndProc(ref m);
//SetCapture(this.Handle)
}else
{
ReleaseCapture();
SetCapture(this.Handle);
foo(p);
}

}else
{
base.WndProc(ref m);
//SetCapture(this.Handle)
}


}
SocketUpEx 2012-08-01
  • 打赏
  • 举报
回复
不明觉厉


uddeeqtkg 2012-08-01
  • 打赏
  • 举报
回复
十分感谢 不过要在窗体内部执行 base.WndProc(ref m)后 在外部点击没有效果了 估计系统自己 ReleaseCapture()了。 在 base.WndProc(ref m)加上 SetCapture(this.Handle);也不管用
是不是得把句柄替换成内部控件的,正在想办法


protected override void WndProc(ref Message m)
{


if (m.Msg == WM_LBUTTONUP)
{
// ReleaseCapture();
Point p = new Point((int)m.LParam);
if (this.ClientRectangle.Contains(p))
{
base.WndProc(ref m);
//SetCapture(this.Handle)
}else
{
ReleaseCapture();
SetCapture(this.Handle);
foo(p);
}

}else
{
base.WndProc(ref m);
//SetCapture(this.Handle)
}


}
[Quote=引用 3 楼 的回复:]

C# code
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
……
[/Quote]
SocketUpEx 2012-08-01
  • 打赏
  • 举报
回复
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

[DllImport("user32.dll")]
public static extern bool ReleaseCapture();

[DllImport("user32.dll")]
public static extern IntPtr SetCapture(IntPtr h);

private readonly Int32 WM_LBUTTONUP = 0x202;

private void Form1_Load(object sender, EventArgs e)
{
SetCapture(this.Handle);
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
ReleaseCapture();
}

protected override void WndProc(ref Message m)
{
if (m.Msg == WM_LBUTTONUP)
{
ReleaseCapture();
MessageBox.Show("你要执行的代码");
SetCapture(this.Handle);
return;
}

base.WndProc(ref m);
}
}
}


SocketUpEx 2012-08-01
  • 打赏
  • 举报
回复
这次好像粘错代码了

SocketUpEx 2012-08-01
  • 打赏
  • 举报
回复
        [DllImport("user32.dll")]
public static extern bool ReleaseCapture();

[DllImport("user32.dll")]
public static extern IntPtr SetCapture(IntPtr h);

private void Form2_Load(object sender, EventArgs e)
{
SetCapture(this.Handle);
}

private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
ReleaseCapture();
}

private void Form2_MouseUp(object sender, MouseEventArgs e)
{
Close();
}


8,834

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 组件/控件开发
社区管理员
  • 组件/控件开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧