繁体   English   中英

处理已创建表单的关闭按键 [C#]

[英]Handle Closing Keypress of a Created Form [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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM