2009-07-02 107 views
0

我已經爲我的窗體 編寫了MouseMove的事件處理程序,但是當我添加一個窗體以形成窗體時,此處理程序不會在面板上移動時運行。 我添加事件處理程序面板和這個工程,但我有幾個面板的形式, 有沒有更容易的解決方案?控件在C#窗口程序中隱藏窗體的事件

+0

你想做什麼? – 2009-07-02 16:06:19

+0

我有兩個面板的表單。我想在它們之間移動一些用戶控件(無需拖動!) – 2009-07-03 03:36:41

回答

0

不,沒有簡單的方法,您應該爲每個需要接收MouseMove事件的控件分配事件處理程序。

1

我認爲你應該能夠「傳播」處理程序,所以你不必重寫每一個代碼。請記住,MouseMove事件有控制相對座標,所以如果您將事件從面板傳遞到表單,則必須將事件中的Y值轉換爲表單座標(類似於減法面板event.X中的.location.X等)。

0

如果您將表格的Capture屬性設置爲true,則無論鼠標下的哪個控件都會接收到所有鼠標輸入。它會在某些操作中失去鼠標捕捉(雖然我不確定時間)。此外,根據財產的文檔,捕捉鼠標時,快捷鍵不應起作用。所以,根據你想要達到的目標,這可能不是首選的方法。

+0

捕獲主要用於拖動操作,因爲在這種情況下,所有其他控件都會失去鼠標互操作性。 – arbiter 2009-07-02 15:40:32

2

不幸的是,WinForms不支持事件冒泡。但是你可以編寫一些代碼來緩解連接事件的任務。

public void AssignMouseMoveEvent(Form form) 
{ 
    foreach(Control control in form.Controls) 
    { 
     if(! (control is Panel)) 
      continue; 

     control.MouseMove += PanelMouseMove; 
    } 
} 

你應該叫上面的代碼通過它您目前的形式,它會分配PanelMouseMove爲所有的面板MouseMove事件的事件處理程序。

+1

請注意,PanelMouseMove事件處理程序中的e.Location將與引發MouseMove事件的控件相關。 – 2009-07-02 15:41:47

+0

我認爲這是作者需要的,不是嗎? – SolutionYogi 2009-07-02 15:44:42

0

假設鼠標開始在表單上而不是在面板上移動 - 這是一個很大的假設 - 當它進入子控件時,您將得到一個MouseLeave事件。如果它仍在表單的邊界內,您可以檢查光標位置並調用鼠標移動代碼。

如果鼠標移動事件在控件上啓動,這不起作用。

1

此代碼工作對我來說(假設你有一個面板和標籤的形式,標籤被命名爲「MouseCoords」

 

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Text; 
using System.Windows.Forms; 

namespace WindowsApplication1 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void ShowCoords(int x, int y) 
     { 
      this.MouseCoords.Text = string.Format("({0}, {1})", x, y); 
     } 

     private void Form1_MouseMove(object sender, MouseEventArgs e) 
     { 
      this.ShowCoords(e.X, e.Y); 
     } 

     protected override void OnControlAdded(ControlEventArgs e) 
     { 
      // hook the mouse move of any control that is added to the form 
      base.OnControlAdded(e); 
      e.Control.MouseMove += new MouseEventHandler(Control_MouseMove); 
     } 

     private void Control_MouseMove(object sender, MouseEventArgs e) 
     { 
      // convert the mouse coords from control codes to screen coords 
      // and then to form coords 
      System.Windows.Forms.Control ctrl = (System.Windows.Forms.Control)sender; 
      Point pt = this.PointToClient(ctrl.PointToScreen(e.Location)); 
      this.ShowCoords(pt.X, pt.Y); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      this.MouseMove += this.Form1_MouseMove; 
     } 
    } 
} 
0

我發現了另一個解決方案:)「在隱藏事件的控件中引發事件」 我在面板中捕獲事件並通過調用onMouseMove來增加窗體的鼠標移動事件