您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)怎么在C#中利用WinForm實(shí)現(xiàn)窗體上控件自由拖動(dòng)功能,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
具體如下:
首先在窗體上放一個(gè)PictrueBox控件,命名為pb1,拖動(dòng)完整代碼如下:
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 { //鼠標(biāo)按下坐標(biāo)(control控件的相對(duì)坐標(biāo)) Point mouseDownPoint = Point.Empty; //顯示拖動(dòng)效果的矩形 Rectangle rect = Rectangle.Empty; //是否正在拖拽 bool isDrag = false; public Form1() { InitializeComponent(); } private void Form1_Paint(object sender, PaintEventArgs e) { if (rect != Rectangle.Empty) { if (isDrag) {//畫一個(gè)和Control一樣大小的黑框 e.Graphics.DrawRectangle(Pens.Black, rect); } else { e.Graphics.DrawRectangle(new Pen(this.BackColor), rect); } } } /// <summary> /// 按下鼠標(biāo)時(shí) /// </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> /// 移過(guò)時(shí) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void pb1_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { isDrag = true; //重新設(shè)置rect的位置,跟隨鼠標(biāo)移動(dòng) rect.Location = getPointToForm(new Point(e.Location.X - mouseDownPoint.X, e.Location.Y - mouseDownPoint.Y)); this.Refresh(); } } /// <summary> /// 釋放鼠標(biāo)按鈕時(shí) /// </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; //移動(dòng)control到放開(kāi)鼠標(biāo)的地方 pb1.Location = rect.Location; this.Refresh(); } reset(); } } //重置變量 private void reset() { mouseDownPoint = Point.Empty; rect = Rectangle.Empty; isDrag = false; } //把相對(duì)與control控件的坐標(biāo),轉(zhuǎn)換成相對(duì)于窗體的坐標(biāo)。 private Point getPointToForm(Point p) { return this.PointToClient(pb1.PointToScreen(p)); } } }
關(guān)于怎么在C#中利用WinForm實(shí)現(xiàn)窗體上控件自由拖動(dòng)功能就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。