1. 程式人生 > >Winform無邊框視窗拖動及改變視窗大小

Winform無邊框視窗拖動及改變視窗大小

Winform無邊框視窗(FormBorderStyle屬性為None)預設是不可以拖動或者改變大小的。

1.      拖動無邊框視窗改變位置

方法1:通過mousedown、mousemove、mouseup、事件來改變視窗Location。

方法2:通過截獲訊息,進行處理,見下面程式碼後半部分。

2.      改變視窗大小

通過重寫視窗訊息處理函式,截獲相關資訊,並進行處理。

程式碼:

const int HTLEFT = 10;

const int HTRIGHT = 11;

const int HTTOP = 12;

const int HTTOPLEFT = 13;

const int

HTTOPRIGHT = 14;

const int HTBOTTOM = 15;

const int HTBOTTOMLEFT = 0x10;

const int HTBOTTOMRIGHT = 17;

protected override voidWndProc(ref Messagem)

{

    switch (m.Msg)

    {

        case 0x0084:

         base.WndProc(refm);

         Point vPoint = newPoint((int)m.LParam& 0xFFFF,

                        (int

)m.LParam >> 16 & 0xFFFF);

         vPoint = PointToClient(vPoint);

         if (vPoint.X <= 5)

             if(vPoint.Y <= 5)

                    m.Result = (IntPtr)HTTOPLEFT;

             elseif (vPoint.Y >= ClientSize.Height - 5)

                   m.Result = (IntPtr)HTBOTTOMLEFT;

              else m.Result = (IntPtr)HTLEFT;

           elseif (vPoint.X >= ClientSize.Width - 5)

               if(vPoint.Y <= 5)

                    m.Result = (IntPtr)HTTOPRIGHT;

               elseif (vPoint.Y >= ClientSize.Height - 5)

                     m.Result = (IntPtr)HTBOTTOMRIGHT;

                else m.Result= (IntPtr)HTRIGHT;

             elseif (vPoint.Y <= 5)

                  m.Result = (IntPtr)HTTOP;

             elseif (vPoint.Y >= ClientSize.Height - 5)

                   m.Result = (IntPtr)HTBOTTOM;

             break;

        case 0x0201://滑鼠左鍵按下的訊息 用於實現拖動視窗功能

               m.Msg = 0x00A1;//更改訊息為非客戶區按下滑鼠

               m.LParam = IntPtr.Zero;//預設值

                 m.WParam = new IntPtr(2);//滑鼠放在標題欄內

                 base.WndProc(ref m);

                 break;

             default:

                 base.WndProc(ref m);

                 break;

            }

       }