這篇文章將為大家詳細講解有關怎么在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實現窗體上控件自由拖動功能就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。