私はパンチに少し遅れていることを知っていますが、今日パネルをタイトルバーとして使用するときにこれに問題がありました。テキストを表示するためのラベル、ピクチャ ボックス、およびいくつかのボタンをすべて Panel 内にネストしましたが、とにかく MouseMove イベントをトラップする必要がありました。
私がやろうと決めたのは、これを行うために再帰メソッド ハンドラを実装することでした。入れ子になったコントロールは 1 レベルしかないため、ばかげたレベルの入れ子に近づくと、これはあまりうまくスケーリングされない可能性があります。
これが私がそれをした方法です:
protected virtual void NestedControl_Mousemove(object sender, MouseEventArgs e)
{
Control current = sender as Control;
//you will need to edit this to identify the true parent of your top-level control. As I was writing a custom UserControl, "this" was my title-bar's parent.
if (current.Parent != this)
{
// Reconstruct the args to get a correct X/Y value.
// you can ignore this if you never need to get e.X/e.Y accurately.
MouseEventArgs newArgs = new MouseEventArgs
(
e.Button,
e.Clicks,
e.X + current.Location.X,
e.Y + current.Location.Y,
e.Delta
);
NestedControl_Mousemove(current.Parent, newArgs);
}
else
{
// My "true" MouseMove handler, called at last.
TitlebarMouseMove(current, e);
}
}
//helper method to basically just ensure all the child controls subscribe to the NestedControl_MouseMove event.
protected virtual void AddNestedMouseHandler(Control root, MouseEventHandler nestedHandler)
{
root.MouseMove += new MouseEventHandler(nestedHandler);
if (root.Controls.Count > 0)
foreach (Control c in root.Controls)
AddNestedMouseHandler(c, nestedHandler);
}
そして、それを設定するのは比較的簡単です:
「真の」ハンドラーを定義します。
protected virtual void TitlebarMouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
this.Text = string.Format("({0}, {1})", e.X, e.Y);
}
}
次に、コントロール イベント サブスクライバーをセットアップします。
//pnlDisplay is my title bar panel.
AddNestedMouseHandler(pnlDisplay, NestedControl_Mousemove);
使い方は比較的簡単で、機能するという事実を保証できます:)