[英]How to Find label control value in Gridview Footer ButtonClick Event
[英]How to raise ButtonClick event by using mnemonic of a label?
在我的C#app中,我有一個帶有助記符的標簽(例如&Path)和一個按鈕。 當用戶按下標簽的助記符時,我想提升ButtonClick事件(例如[Alt],然后是[P])。 但我沒有找到任何標簽事件來處理這種情況。 使用按鈕的OnFocus事件不是一個選項,因為用戶可以使用[Tab]鍵進行導航。
那么有沒有辦法實現我想要的?
提前致謝。
或者您可以使用以垃圾p
開頭的東西命名您的按鈕,然后將它放在&
之前, alt + p
將觸發btn_Click
事件處理程序
編輯:這樣的事:)
標簽上的助記符只關注具有下一個TabIndex
的控件,而這就是它的全部功能。 您無法使用它直接調用任何內容(例如按鈕的單擊事件)。
您可以使用此行為的知識來模擬您想要實現的目標。 我們的想法是在您的表單上放置一個輕量級,可聚焦的控件,該控件具有緊跟在標簽之后的TabIndex
,但位於不可見的位置(如左上角之外)。 然后在隱藏控件的焦點事件上做你想做的事情。
這是一個完整的獨立示例。 在這種情況下,隱藏控件將是一個復選框。
using System;
using System.Drawing;
using System.Windows.Forms;
public class MyForm : Form
{
public MyForm()
{
targetLabel = new Label()
{
Text = "&Label",
TabIndex = 10,
AutoSize = true,
Location = new Point(12, 17),
};
// you don't need to keep an instance variable
var hiddenControl = new CheckBox()
{
Text = String.Empty,
TabIndex = 11, // immediately follows target label
TabStop = false, // prevent tabbing to control
Location = new Point(-100, -100), // put somewhere not visible
};
hiddenControl.GotFocus += (sender, e) =>
{
// simulate clicking on the target button
targetButton.Focus();
targetButton.PerformClick();
};
targetButton = new Button()
{
Text = "&Click",
TabIndex = 20,
AutoSize = true,
Location = new Point(53, 12),
};
targetButton.Click += (sender, e) =>
{
MessageBox.Show("Target Clicked!");
};
dummyButton = new Button()
{
Text = "&Another Button",
TabIndex = 0,
AutoSize = true,
Location = new Point(134, 12),
};
dummyButton.Click += (sender, e) =>
{
MessageBox.Show("Another Button Clicked!");
};
this.Controls.Add(targetLabel);
this.Controls.Add(hiddenControl);
this.Controls.Add(targetButton);
this.Controls.Add(dummyButton);
}
private Label targetLabel;
private Button targetButton;
private Button dummyButton;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyForm());
}
}
您沒有指定項目的類型(Winforms / WPF),但我認為所有這些類型的解決方案都是相同的:
您應該將表單上的KeyPreview
設置為true,並將KeyUp
事件處理程序中的按鍵檢查為nelow:
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.P && e.Alt == true)
{
MessageBox.Show("Got it");
}
}
在此示例中,如果按下Alt + P,您將收到消息框
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.