设置对象的位置与visual c#中的光标位置相同
本文关键字:位置 光标 visual 对象 设置 | 更新日期: 2023-09-27 18:10:10
我想让我的按钮位置与鼠标左键按下时的光标位置相同所以我这样写:
private void button1_MouseDown(object sender, MouseEventArgs e)
{
button1.Location = Cursor.Position;
}
但是按钮移动的距离比光标的位置远,而且它只出现一次,我不能用鼠标自由移动按钮。
有什么问题吗?
说明我的评论:
private bool _isAllowMove = false;
...
button1.MouseMove += new MouseEventHandler((object sender, MouseEventArgs e) =>
{
if(!_isAllowMove) {
return;
}
button1.Location = this.PointToClient(Cursor.Position);
});
button1.MouseDown += new MouseEventHandler((object sender, MouseEventArgs e) =>
{
_isAllowMove = true;
});
button1.MouseUp += new MouseEventHandler((object sender, MouseEventArgs e) =>
{
_isAllowMove = false;
});
//其他完整的注释示例
动态设置所有按钮的事件:
public partial class Form1: Form
{
public Form1()
{
InitializeComponent();
//...
setHandler(button1);
setHandler(button2);
//...
}
protected void setHandler(Button btn)
{
// TODO: synchronise thread & remove old handler
/**
* e.g.:
* lock(_eLock){
* btn.MouseMove -= new MouseEventHandler(..)
* btn.MouseMove += new MouseEventHandler(..)
* }
*
*/
// NOTE: the 'AllowDrop' property only for example -
// you can replace this with your custom components - e.g. ButtonCustom()
/**
* public class ButtonCustom: Button
* {
* ...
* bool AllowMove { get; set; }
* ...
* }
*
*/
btn.AllowDrop = false;
btn.MouseMove += new MouseEventHandler((object sender, MouseEventArgs e) => {
if(!btn.AllowDrop) {
return;
}
btn.Location = this.PointToClient(Cursor.Position);
});
btn.MouseDown += new MouseEventHandler((object sender, MouseEventArgs e) => {
btn.AllowDrop = true;
});
btn.MouseUp += new MouseEventHandler((object sender, MouseEventArgs e) => {
btn.AllowDrop = false;
});
}
}