zoukankan      html  css  js  c++  java
  • WinForm

    为了界面的好看,有时候需要将窗体FormBorderStyle属性设为None,这样就可以根据自己的喜欢来设计界面。但这样窗体无法进行移动的。而且默认的窗体(FormBorderStyle=Sizable)只有点击窗体边框才能移动,点击内容界面也是无法移动。根据网友们的介绍和总结,有两种比较简单的实现方法。

    方法一:通过记录窗体的位置,然后利用MouseDown、MouseUp、MouseMove这三个事件实现窗体的移动。

     1 bool isMouseDown = false;
     2 Point currentFormLocation = new Point(); //当前窗体位置
     3 Point currentMouseOffset = new Point(); //当前鼠标的按下位置
     4 private void Form1_MouseDown(object sender, MouseEventArgs e)
     5 {
     6     if (e.Button == MouseButtons.Left)
     7     {
     8         isMouseDown = true;
     9         currentFormLocation = this.Location;
    10         currentMouseOffset = Control.MousePosition;
    11     }
    12 }
    13 
    14 private void Form1_MouseUp(object sender, MouseEventArgs e)
    15 {
    16     isMouseDown = false;
    17 }
    18 
    19 private void Form1_MouseMove(object sender, MouseEventArgs e)
    20 {
    21     int rangeX = 0, rangeY = 0; //计算当前鼠标光标的位移,让窗体进行相同大小的位移
    22     if (isMouseDown)
    23     {
    24         Point pt = Control.MousePosition;
    25         rangeX = currentMouseOffset.X - pt.X;
    26         rangeY = currentMouseOffset.Y - pt.Y;
    27         this.Location = new Point(currentFormLocation.X - rangeX, currentFormLocation.Y - rangeY);
    28     }
    29 }

    第二种方法:利用windows的消息机制来实现(转自:http://www.cnblogs.com/techmango/archive/2012/03/31/2427523.html)

    //首先﹐.定义鼠標左鍵按下時的Message标识﹔其次﹐在Form1_MouseDown方法﹐讓操作系統誤以為是按下标题栏。
    //1.定义鼠標左鍵按下時的Message标识
    private const int WM_NCLBUTTONDOWN = 0XA1;   //.定义鼠標左鍵按下
    private const int HTCAPTION = 2;
    
    //2.讓操作系統誤以為是按下标题栏
    private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
    {
        //為當前的應用程序釋放鼠標鋪獲
        ReleaseCapture();
        //發送消息﹐讓系統誤以為在标题栏上按下鼠標
        SendMessage((int)this.Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0);
    }
    
    //3.申明程序中所Windows的API函數
    [DllImport("user32.dll",EntryPoint="SendMessageA")]
    private static extern int SendMessage(int hwnd, int wMsg, int wParam, int lParam);
    
    [DllImport("user32.dll")]
    private static extern int ReleaseCapture();
  • 相关阅读:
    C#磁吸屏幕窗体类库
    准备
    我写的诗
    How to turn off a laptop keyboard
    How to tell which commit a tag points to in Git?
    Why should I care about lightweight vs. annotated tags?
    How to get rid of “would clobber existing tag”
    Facebook, Google and Twitter threaten to leave Hong Kong over privacy law changes
    The need for legislative reform on secrecy orders
    Can a foreign key be NULL and/or duplicate?
  • 原文地址:https://www.cnblogs.com/tracine0513/p/3621913.html
Copyright © 2011-2022 走看看