解決Windows Forms中基於Panel的使用者控制焦點問題
在Windows Forms應用程式中,基於Panel的使用者控制項預設無法接收鍵盤焦點,這會影響鍵盤導覽的互動。為了解決這個問題,開發者需要找到一種優雅的方案來使基於Panel的使用者控制能夠獲得焦點。
最佳方法是擴展Panel類別並仔細實作特定事件。以下程式碼片段示範如何實現:
<code class="language-csharp">using System; using System.Drawing; using System.Windows.Forms; class SelectablePanel : Panel { public SelectablePanel() { this.SetStyle(ControlStyles.Selectable, true); this.TabStop = true; } protected override void OnMouseDown(MouseEventArgs e) { this.Focus(); base.OnMouseDown(e); } protected override bool IsInputKey(Keys keyData) { if (keyData == Keys.Up || keyData == Keys.Down) return true; if (keyData == Keys.Left || keyData == Keys.Right) return true; return base.IsInputKey(keyData); } protected override void OnEnter(EventArgs e) { this.Invalidate(); base.OnEnter(e); } protected override void OnLeave(EventArgs e) { this.Invalidate(); base.OnLeave(e); } protected override void OnPaint(PaintEventArgs pe) { base.OnPaint(pe); if (this.Focused) { var rc = this.ClientRectangle; rc.Inflate(-2, -2); ControlPaint.DrawFocusRectangle(pe.Graphics, rc); } } }</code>
這段程式碼增強了基礎Panel類別:
透過這些重寫,SelectablePanel使用者控制項現在能夠獲得焦點並按預期處理鍵盤輸入,即使它繼承自Panel。此解決方案提供了一種優雅有效的方法來解決基於Panel的使用者控制項的焦點問題。
以上是如何讓 Windows 窗體中基於面板的使用者控制項接收鍵盤焦點?的詳細內容。更多資訊請關注PHP中文網其他相關文章!