c# - 处理已创建表单的关闭按键 [C#]
问题描述
我有一个我创建的表单,它是一个简单的提示。它做得很好,但我希望能够通过转义键关闭它。
我不确定如何执行此操作,因为我无法引用它。
这是代码:
// Create Prompt
public static string ShowDialog(string text, string caption, bool LimitLength = false)
{
Form prompt = new Form()
{
Width = 500,
Height = 150,
FormBorderStyle = FormBorderStyle.FixedDialog,
Text = caption,
StartPosition = FormStartPosition.CenterScreen
};
Label textLabel = new Label() { Left = 50, Top = 20, Text = text };
Label charlimit = new Label() { Left = 50, Top = 80, Text = "255" };
TextBox textBox = new TextBox() { Left = 50, Top = 50, Width = 400 };
Button confirmation = new Button() { Text = "Ok", Left = 350, Width = 100, Top = 70, DialogResult = DialogResult.OK };
confirmation.Click += (sender, e) => { if (textBox.Text != "") { prompt.Close(); } };
textBox.TextChanged += (sender, e) => { charlimit.Text = (255 - textBox.Text.Length).ToString(); };
prompt.KeyDown += new KeyEventHandler(Prompt_KeyDown);
prompt.Controls.Add(textBox);
prompt.Controls.Add(confirmation);
prompt.Controls.Add(textLabel);
prompt.AcceptButton = confirmation;
if (LimitLength)
{
prompt.Controls.Add(charlimit);
textBox.MaxLength = 255;
} // Adjust for MSG command.
return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : "";
}
// Prompt Key Handler
public static void Prompt_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
// Close the Prompt..
}
}
解决方案
您可能应该为您的 gui 添加一个取消按钮:
Button cancel = new Button() { Text = "Cancel",
Left = 350, Width = 100, Top = 100,
DialogResult = DialogResult.Cancel };
将其添加到集合中并设置 Form 的 CancelButton 属性
prompt.Controls.Add(cancel);
prompt.AcceptButton = confirmation;
prompt.CancelButton = cancel;
推荐阅读
- java - 如何修复嵌套的?
- .net - 如何访问附加了属性的参数?
- docker - docker-compose: varnish+apache2 返回 503 错误`Backend fetch failed`
- full-text-search - 在 ClickHouse 中搜索文本时内存不足
- azure-cosmosdb - CosmosDb 和 RU 用于同一查询
- flutter - 应用再次启动时如何使用共享偏好打开特定屏幕
- json - DRF:发出外部请求并构建序列化程序
- node.js - 如何在 Op 中分配 Sequelize 的比较运算符
- javascript - 如何处理 Caesars Cipher (Javascript) 中的负偏移
- c# - ASP.NET Core Razor 页面 - 不绑定 POST 请求