c#

位置:IT落伍者 >> c# >> 浏览文章

C#实现窗体和任意控件的拖动


发布日期:2021年03月15日
 
C#实现窗体和任意控件的拖动

程序内有大部分注释了欢迎大家指正了!

Code

[copy to clipboard]

CODE:

using System;

using SystemDrawing;

using SystemWindowsForms;

namespace YokerFormUtils

{

/**//// <summary>

/// <para>说明窗体拖动类通过这个类提供的方法实现窗体上任意控件可辅助拖动窗体</para>

/// <para>作者YokerWu</para>

/// <para>原创地址</para>

/// </summary>

public class dragFormClass

{

private static bool isMouseDown = false;

private static Point mouseOffset;

private static Form _form;

public dragFormClass() { }

/**//// <summary>

/// 在窗体上增加拖拽事件

/// </summary>

/// <param name=control>控件对象</param>

public static void bindControl(Control control)

{

//如果控件为空

if (control == null)

{

return;

}

_form = controlFindForm();

//增加鼠标拖动窗体移动事件

controlMouseMove += new MouseEventHandler(control_MouseMove);

controlMouseDown += new MouseEventHandler(control_MouseDown);

controlMouseUp += new MouseEventHandler(control_MouseUp);

}

/**//// <summary>

/// 鼠标按下之时保存鼠标相对于窗体的位置

/// </summary>

/// <param name=sender></param>

/// <param name=e></param>

private static void control_MouseDown(object sender MouseEventArgs e)

{

if (eButton == MouseButtonsLeft)

{

Control control = sender as Control;

int offsetX = eX;

int offsetY = eY;

//判断是窗体还是控件从而改进鼠标相对于窗体的位置

if (!(control is SystemWindowsFormsForm))

{

offsetX = offsetX controlLeft;

offsetY = offsetY controlTop;

}

//判断窗体有没有标题栏从而改进鼠标相对于窗体的位置

if (_formFormBorderStyle != FormBorderStyleNone)

{

offsetX = offsetX SystemInformationFrameBorderSizeWidth;

offsetY = offsetY SystemInformationFrameBorderSizeHeight SystemInformationCaptionHeight;

}

mouseOffset = new Point(offsetX offsetY);

isMouseDown = true;

}

}

/**//// <summary>

/// 移动鼠标的时候改变窗体位置

/// </summary>

/// <param name=sender></param>

/// <param name=e></param>

private static void control_MouseMove(object sender MouseEventArgs e)

{

if (isMouseDown)

{

Point mouse = ControlMousePosition;

mouseOffset(mouseOffsetX mouseOffsetY);

_formLocation = mouse;

}

}

/**//// <summary>

/// 松开鼠标的时候重设事件

/// </summary>

/// <param name=sender></param>

/// <param name=e></param>

private static void control_MouseUp(object sender MouseEventArgs e)

{

if (eButton == MouseButtonsLeft)

{

isMouseDown = false;

}

}

}

}

               

上一篇:c#学习体会:使用 ref 和 out 传递数组

下一篇:.NET下基于API封装的DirectUIHWND窗体访问