2009-10-06 87 views
0

我有一個沒有邊框,標題欄,菜單等的Windows窗體。我希望用戶能夠按住CTRL鍵,左鍵單擊表單上的任意位置並拖動它,移動。任何想法如何做到這一點?我想這一點,但它閃爍,不少:如何在按住鼠標的同時移動表單?

private void HiddenForm_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) 
    { 
     if (e.Button == System.Windows.Forms.MouseButtons.Left) 
     { 
      this.SuspendLayout(); 
      Point xy = new Point(this.Location.X + (e.X - this.Location.X), this.Location.Y + (e.Y - this.Location.Y)); 
      this.Location = xy; 
      this.ResumeLayout(true); 
     } 
    } 

回答

4

試試這個

using System.Runtime.InteropServices; 

const int HT_CAPTION = 0x2; 
const int WM_NCLBUTTONDOWN = 0xA1; 

[DllImportAttribute("user32.dll")] 
public static extern int SendMessage(IntPtr hWnd,int Msg, int wParam, int lParam); 
[DllImportAttribute("user32.dll")] 
public static extern bool ReleaseCapture();  


private void Form1_MouseDown(object sender, MouseEventArgs e) 
{ 
    if (e.Button == MouseButtons.Left) 
    { 
    ReleaseCapture(); 
    SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0); 
    } 
} 

更新

ReleaseCapture()函數釋放從一個窗口在當前線程和恢復鼠標捕獲正常的鼠標輸入處理。捕獲鼠標的窗口接收所有鼠標輸入,而不管光標的位置如何,除非在另一個線程的窗口中單擊鼠標按鈕時鼠標按鈕被點擊。

當在窗口的非客戶區域上進行鼠標左鍵單擊時,WM_NCLBUTTONDOWN消息被髮送到窗口。 wParam指定了命中測試枚舉值。我們通過了HTCAPTION,並且lParam指定了光標位置,我們將其作爲0傳遞,以確保它位於標題欄中。

+0

這很好,只是好奇它在做什麼? – esac 2009-10-06 23:35:47

+0

它是在默認的窗口過程中,在窗口的「標題」非客戶區發生鼠標停止事件。 儘管如果你想要正確的實現,你應該添加你自己的消息處理鉤子並且處理WM_NCHITTEST消息來返回HT_CAPTION你想要啓用表單拖動的窗體區域。 – 2009-10-07 00:01:06

+0

+1甜蜜......你贏了:)我甚至沒有得到正確的數學LOL。 – 2009-10-07 00:59:03