我在用着MouseMove
, MouseUp
, MouseDown
移动无边界表单的事件(如此处的示例)。
它工作得很好,但对于 ListView,只有当我单击列表中的项目(其文本)时它才有效。如果我单击不包含项目的 ListView 的空间,它将不起作用。
有可能解决这个问题的方法吗?
private bool mouseDown;
private Point lastLocation;
private void ListView1_MouseDown(object sender, MouseEventArgs e)
{
mouseDown = true;
lastLocation = e.Location;
}
private void ListView1_MouseMove(object sender, MouseEventArgs e)
{
if(mouseDown)
{
this.Location = new Point(
(this.Location.X - lastLocation.X) + e.X, (this.Location.Y - lastLocation.Y) + e.Y);
this.Update();
}
}
private void ListView1_MouseUp(object sender, MouseEventArgs e)
{
mouseDown = false;
}
要移动表单,单击并拖动任何控件,您可以实现IMessageFilter接口 https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.imessagefilter。您将在消息发送到目标控件之前收到消息(可以选择抑制它们,返回true
).
实施要求您实施预过滤消息 https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.imessagefilter.prefiltermessage.
当消息出现时存储当前鼠标位置WM_LBUTTONDOWN
并在表格出现时移动表格WM_MOUSEMOVE
,如果仍然按下左侧按钮(当前按下的按钮在WParam
,请参阅有关此的文档)。
Use 应用程序.AddMessageFilter https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.application.addmessagefilter注册实现该接口的类(在本例中为表单本身)。在这里,它被称为OnHandleCreated
.
Call 应用程序.删除消息过滤器 https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.application.removemessagefilter取下过滤器。在这里,请来了OnHandleDestroyed
.
请注意,我已经使用过Capture = true;
in WM_MOUSEMOVE
,因此按下鼠标左键并拖动(例如,按钮控件)不会导致(在本例中)单击事件。
如果您不喜欢它,请修改它。
笔记:
正如 Reza Aghaei 建议的那样,如果您将 ListView 设置为MultiSelect = false
,然后您可以单击其上的任意位置来拖动表单。
public partial class SomeForm : Form, IMessageFilter
{
private const int WM_MOUSEMOVE = 0x0200;
private const int WM_LBUTTONDOWN = 0x0201;
Point mouseDownPos = Point.Empty;
public bool PreFilterMessage(ref Message m) {
switch (m.Msg) {
case WM_LBUTTONDOWN:
mouseDownPos = PointToClient(MousePosition);
break;
case WM_MOUSEMOVE:
if ((m.WParam.ToInt32() & 1) != 1) break;
Capture = true;
var p = PointToClient(MousePosition);
Location = new Point(Left + p.X - mouseDownPos.X, Top + p.Y - mouseDownPos.Y);
break;
}
return false;
}
protected override void OnHandleCreated(EventArgs e) {
base.OnHandleCreated(e);
if (!DesignMode) Application.AddMessageFilter(this);
}
protected override void OnHandleDestroyed(EventArgs e) {
if (!DesignMode) Application.RemoveMessageFilter(this);
base.OnHandleDestroyed(e);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)