WPF:Windows 演示基础 | C 夏普:C#
//Variables ----------------------
static System.Boolean MMove = false;
static System.Windows.Point MPoint1;
static System.Windows.Point MPoint2;
static System.Windows.Controls.Control MyControl = null;
static System.Windows.Controls.Canvas MyCanvas = null;
[?]在应用程序中完成移动控制所需的静态变量;
--- MyCanvas必须在您的应用程序启动时指定;(或使用前的任何时候)
//MouseEvents --------------------
yourControl.MouseDown += new System.Windows.Input.MouseButtonEventHandler(MouseDown);
yourControl.MouseUp += new System.Windows.Input.MouseButtonEventHandler(MouseUp);
yourControl.PreviewMouseMove += new System.Windows.Input.MouseEventHandler(MouseMove);
[?]要分配给您的控件的鼠标事件;
//MouseDown EventHandler ---------
static void MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (sender is UserControl1)
{
//get control clicked
MyControl = (UserControl1)sender;
//get coordinates
MPoint1 = e.GetPosition(MCanvas);
MPoint2 = e.GetPosition(MyControl);
//update coordinates
MPoint1.X -= MyControl.Margin.Left + MPoint2.X;
MPoint1.Y -= MyControl.Margin.Top + MPoint2.Y;
//prevent mouse loosing focus of the control
System.Windows.Input.Mouse.Capture(MyControl);
//enable move indicator
MMove = true;
}
}
//MouseMove EventHandler ---------
static void MouseMove(object sender, System.Windows.Input.MouseEventArgs e) {
if (sender is UserControl1) {
//check move indicator
if (MMove == true)
{
//get control moved
MyControl = (UserControl1)sender;
//get container pointer
var currentPoint = e.GetPosition(MCanvas);
//check which mouse button is pressed
if (e.LeftButton == System.Windows.Input.MouseButtonState.Pressed)
{
//update control margin thickness
MyControl.Margin = new System.Windows.Thickness(
currentPoint.X - MPoint1.X - MPoint2.X,
currentPoint.Y - MPoint1.Y - MPoint2.Y,
MyControl.Margin.Right,
MyControl.Margin.Bottom
);
}
}
}
}
//MouseUp EventHandler ---------
static void MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
MMove = false;
MyControl = null;
System.Windows.Input.Mouse.Capture(null);
}
[?] EventHandler用于执行移动控件的逻辑;