我已经构建了一个自定义控件,我希望允许人们单击并拖动我的控件,就像在窗口标题栏上拖动一样。做这个的最好方式是什么?
到目前为止,我未能成功地利用鼠标向下、向上和移动事件来破译何时需要移动窗口。
除了我的其他答案之外,您还可以在控件中手动执行此操作,如下所示:
Point dragOffset;
protected override void OnMouseDown(MouseEventArgs e) {
base.OnMouseDown(e);
if (e.Button == MouseButtons.Left) {
dragOffset = this.PointToScreen(e.Location);
var formLocation = FindForm().Location;
dragOffset.X -= formLocation.X;
dragOffset.Y -= formLocation.Y;
}
}
protected override void OnMouseMove(MouseEventArgs e) {
base.OnMouseMove(e);
if (e.Button == MouseButtons.Left) {
Point newLocation = this.PointToScreen(e.Location);
newLocation.X -= dragOffset.X;
newLocation.Y -= dragOffset.Y;
FindForm().Location = newLocation;
}
}
EDIT:经过测试并修复 - 现在确实有效。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)