在VC#2010中移動無標題欄的窗口

/***********************************************************
*說明: 在VC#2010中移動無標題欄的窗口
*備註:測試代碼的程序的項目名爲:MoveNoTitle
*原理:捕獲鼠標事件,編寫相應的代碼
*做者:袁培榮 yuanpeirong@vip.qq.com
*修改時間:2011年09月25日
***********************************************************/

/***********************************************************
 首先,咱們打開VS2010,選擇新建->項目,選擇語言爲Visual C#,
 開發模式爲Windows,選擇開發Windows窗體應用程序,
 設置項目名稱爲:MoveNoTitle,進入開發環境
 咱們先在窗體上加一個按鈕,用來關閉窗體。
 C#的窗體只在標題欄中有關閉按鈕,這裏咱們的窗體是無標題欄的
 那麼咱們就沒有關閉按鈕來關閉程序了,這樣是危險的
 所以咱們要加個按鈕來關閉窗體
 讀者能夠用別的方法來關閉窗體,只要有關閉窗體這個功能就行。
***********************************************************/

/***********************************************************
 而後,咱們爲窗體添加四個事件,記住,必定要用嚮導添加,不然
 下面的代碼不起做用,除非你在主函數上聲明這些事件。
 事件分別爲:button1_Click
             Form1_MouseMove
			 Form1_MouseUp
			 Form1_MouseLeave
			 Form1_MouseDown
***********************************************************/

//咱們在文件Form1.cs中加入以下代碼便可
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 MoveNoTitle
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        bool beginMove = false;//初始化
        int currentXPosition;
        int currentYPosition;
        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            if (beginMove)
            {
                this.Left += MousePosition.X - currentXPosition;//根據鼠標x座標肯定窗體的左邊座標x
                this.Top += MousePosition.Y - currentYPosition;//根據鼠標的y座標窗體的頂部,即Y座標
                currentXPosition = MousePosition.X;
                currentYPosition = MousePosition.Y;
            }
        }

        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            beginMove = false;//中止移動
        }

        private void Form1_MouseLeave(object sender, EventArgs e)
        {
            currentXPosition = 0; //設置初始狀態
            currentYPosition = 0;
            beginMove = false;
        }

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            beginMove = true;
            currentXPosition = MousePosition.X;//鼠標的x座標爲當前窗體左上角x座標
            currentYPosition = MousePosition.Y;//鼠標的y座標爲當前窗體左上角y座標

        }
    }
}
相關文章
相關標籤/搜索