本文實例講述了C# WinForm實現窗體上控件自由拖動功能。分享給大家供大家參考,具體如下:
說明:首先在窗體上放一個PictrueBox控件,命名為pb1,拖動完整代碼如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WinFormDrag
{
public partial class Form1 : Form
{
//鼠標按下坐標(control控件的相對坐標)
Point mouseDownPoint = Point.Empty;
//顯示拖動效果的矩形
Rectangle rect = Rectangle.Empty;
//是否正在拖拽
bool isDrag = false;
public Form1()
{
InitializeComponent();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
if (rect != Rectangle.Empty)
{
if (isDrag)
{//畫一個和Control一樣大小的黑框
e.Graphics.DrawRectangle(Pens.Black, rect);
}
else
{
e.Graphics.DrawRectangle(new Pen(this.BackColor), rect);
}
}
}
/// <summary>
/// 按下鼠標時
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void pb1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mouseDownPoint = e.Location;
//記錄控件的大小
rect = pb1.Bounds;
}
}
/// <summary>
/// 移過時
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void pb1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isDrag = true;
//重新設置rect的位置,跟隨鼠標移動
rect.Location = getPointToForm(new Point(e.Location.X - mouseDownPoint.X, e.Location.Y - mouseDownPoint.Y));
this.Refresh();
}
}
/// <summary>
/// 釋放鼠標按鈕時
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void pb1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (isDrag)
{
isDrag = false;
//移動control到放開鼠標的地方
pb1.Location = rect.Location;
this.Refresh();
}
reset();
}
}
//重置變量
private void reset()
{
mouseDownPoint = Point.Empty;
rect = Rectangle.Empty;
isDrag = false;
}
//把相對與control控件的坐標,轉換成相對于窗體的坐標。
private Point getPointToForm(Point p)
{
return this.PointToClient(pb1.PointToScreen(p));
}
}
}
更多關于C#相關內容感興趣的讀者可查看本站專題:《WinForm控件用法總結》、《C#窗體操作技巧匯總》、《C#數據結構與算法教程》、《C#常見控件用法教程》、《C#面向對象程序設計入門教程》及《C#程序設計之線程使用技巧總結》
希望本文所述對大家C#程序設計有所幫助。
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!