WinForm 求教怎么捕获窗口外的鼠标事件 SetCapture
我有一个模态对话框想在鼠标点击窗口外的地方时执行一段代码
var form=new Form1();
form.showDialog();
有人说用 SetCapture();
我在form中加了SetCapture(this) 后该怎么做
WndProc(ref Message m) 里还是得不到鼠标的消息
[最优解释]
[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();
}[其他解释]
这次好像粘错代码了
[其他解释]
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);
}
}
}
[其他解释]
十分感谢 不过要在窗体内部执行 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)
}
}
[其他解释]
不明觉厉
[其他解释]
遇到一个问题在窗体内部的控件的事件得不到响应了,比如窗体上的 按钮的点击没反应,文本框的不到焦点
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)
}
}
[其他解释]
写在lostfocus里。