您的位置:首页 > 编程语言 > C#

Windows Form Tips: 无边框窗口实现用鼠标拖拽的功能

2014-01-12 23:58 323 查看
有时候,为了达到一些特定的UI效果,我们可能会将一个Windows Form设定为无边框的形式(FormBorderStyle设置为None),但这时,窗口也将失去正常的用鼠标拖拽的行为。但下面这个例子可以让无边框窗口的鼠标拖拽功能又恢复回来。注意这个例子只支持按住鼠标左键拖拽。

假设窗口为Form1,我们为Form1增加MouseDown的响应函数Form1_MouseDown,以及MouseMove的响应函数Form1_MouseMove。

代码如下:

namespace Demo1
{
using System.Drawing;
using System.Windows.Forms;

public partial class Form1 : Form
{
private Point startPoint;

public Form1()
{
this.InitializeComponent();
}

/// <summary>
/// Handles the MouseDown event of the Form1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
startPoint = new Point(
-e.X + SystemInformation.FrameBorderSize.Width,
-e.Y - SystemInformation.FrameBorderSize.Height);
}

/// <summary>
/// Handles the MouseMove event of the Form1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Point mousePosition = Control.MousePosition;
mousePosition.Offset(this.startPoint.X, this.startPoint.Y);
this.Location = mousePosition;
}
}
}
}


然后你可以试试,这个无边框窗口是可以按住鼠标左键拖拽的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Windows Form .Net C#