国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C# WinForm實現窗體上控件自由拖動功能示例

2020-01-24 00:35:18
字體:
來源:轉載
供稿:網友

本文實例講述了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#程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 辽宁省| 鄱阳县| 南澳县| 阳春市| 闻喜县| 尼木县| 丰顺县| 黎城县| 隆子县| 木兰县| 苗栗市| 邹平县| 老河口市| 依安县| 华安县| 淮滨县| 双流县| 武义县| 扎兰屯市| 沂源县| 江西省| 扎鲁特旗| 葫芦岛市| 陆良县| 沅陵县| 嘉兴市| 三河市| 保山市| 吕梁市| 肇庆市| 顺平县| 县级市| 共和县| 镇江市| 固始县| 肇州县| 宝山区| 于田县| 天全县| 蕲春县| 嘉荫县|