【发布时间】:2016-03-11 02:27:25
【问题描述】:
我有一个创建几个按钮的简单程序,它允许您使用自定义类来移动它们。这些按钮被添加到面板中,他们应该不能离开它。但是,当我仍然按住鼠标左键时,我似乎无法做到这一点,即我在面板边界的边缘停止控件并禁用可拖动功能,但是一旦我释放鼠标按钮,它实际上就会采取行动。这是代码:
private void CreateButtons(IList<Button> inputArray)
{
for (int i = 0; i < inputArray.Count; i++)
{
inputArray[i] = new Button
{
Height = 100,
Width = 100
};
PuzzelHolder.Controls.Add(inputArray[i]);
inputArray[i].Text = Values[i].ToString();
inputArray[i].TextAlign = ContentAlignment.MiddleCenter;
inputArray[i].Draggable(true);
inputArray[i].Location = new Point(20, 20);
inputArray[i].MouseDown += Button_Mouse_Down;
inputArray[i].MouseUp += Button_Mouse_Up;
//horizontal += inputArray[i].Width;
}
}
这就是我创建按钮的方式,你可以看到它们有与之关联的事件:
private void Button_Mouse_Down(object sender, MouseEventArgs e)
{
if (IsLeaving(((Control) sender), PuzzelHolder))
{
((Control) sender).Location = new Point(((Control) sender).Location.X, ((Control) sender).Location.Y);
((Control) sender).Draggable(false);
}
else
{
((Control) sender).Draggable(true);
}
}
private void Button_Mouse_Up(object sender, MouseEventArgs e)
{
((Control)sender).Draggable(true);
}
这也是 Draggable 类:
public static class ControlExtension
{
private static readonly Dictionary<Control, bool> draggables =
new Dictionary<Control, bool>();
private static System.Drawing.Size mouseOffset;
public static void Draggable(this Control control, bool Enable)
{
if (Enable)
{
// enable drag feature
if (draggables.ContainsKey(control))
{ // return if control is already draggable
return;
}
// 'false' - initial state is 'not dragging'
draggables.Add(control, false);
// assign required event handlersnnn
control.MouseDown += control_MouseDown;
control.MouseUp += control_MouseUp;
control.MouseMove += control_MouseMove;
}
else
{
// disable drag feature
if (!draggables.ContainsKey(control))
{ // return if control is not draggable
return;
}
// remove event handlers
control.MouseDown -= control_MouseDown;
control.MouseUp -= control_MouseUp;
control.MouseMove -= control_MouseMove;
draggables.Remove(control);
}
}
private static void control_MouseDown(object sender, MouseEventArgs e)
{
mouseOffset = new System.Drawing.Size(e.Location);
// turning on dragging
draggables[(Control)sender] = true;
}
private static void control_MouseUp(object sender, MouseEventArgs e)
{
// turning off dragging
draggables[(Control)sender] = false;
}
private static void control_MouseMove(object sender, MouseEventArgs e)
{
// only if dragging is turned on
if (draggables[(Control)sender])
{
// calculations of control's new position
var newLocationOffset = e.Location - mouseOffset;
((Control)sender).Left += newLocationOffset.X;
((Control)sender).Top += newLocationOffset.Y;
}
}
}
【问题讨论】:
-
您是否尝试过使用 MDI 容器?
标签: c# winforms events key controls