【问题标题】:Application.Run() and Key Press eventsApplication.Run() 和 Key Press 事件
【发布时间】:2014-09-16 11:01:54
【问题描述】:

我有一个带有 KeyPress 事件控件的表单。例如:

    private void MyTextBoxKeyPress(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            *****
        }
    }

从这个“父”表单我调用另一个表单:

Application.Run(new ChildForm());

现在我选择一个父窗体的控件,然后按 Enter 按钮。但是什么都没有?按键不触发事件。
在这两种形式中,我都有:

KeyPreview=false;

我在这里做错了什么?如何以父形式拍摄按键事件?

【问题讨论】:

  • 我不确定我是否得到了这个问题,但是当你按下一个键时,你有没有关注 keypress 事件的控件?如果没有,则不会触发该事件。
  • @NahuelIanni 是的,在按 Enter 键之前,我用鼠标选择了我的控件。

标签: c#


【解决方案1】:

这对我来说很好,不同的是它是按键事件,所以它包含 KeypressEventArgs

    private void MyTextBoxKeyPress(object sender, KeyPressEventArgs e)
    {
         if (e.KeyChar == (char)Keys.Enter)
        {
             *****

        } 
     }

按键事件

   private void MyTextBoxKeyPress(object sender, KeyEventArgs e)
    {
        if (e.KeyValue == (char)Keys.Enter)
        {
/*only use Apllication.run(..) in Application entry point when starting Application. it makes current thread to communicate with window and main thread is enough to do it .
 * if Form layout is already there
 *
 */
            new Form2().Show();


/*
 * if you want to make new Form  programmatically and only resume from same line if form is closed
 *
 */
            Form form = new Form();
            form.ShowDialog();

        }
    }

【讨论】:

  • 哦,我要停止使用 Application.Run ((。感谢您的解决方案。
【解决方案2】:

仅使用 1 个Application.Run(这是您的主表单)。

您可以通过创建并显示其他表单来显示它:

Form frm = new ChildForm();
frm.Show()

【讨论】:

    【解决方案3】:

    首先你不能使用“Application.Run”来显示新的表单。 你应该使用 froms 的“显示”方法。 下面的代码应该可以帮助你。

    我有 2 种形式,如你所说。 第一个是名为“parentForm”的父表单,第二个是 childForm 从 parentForm 调用 childForm。“我调用 parentForm 加载” 并从 parentForm 为 childForm 设置事件委托并抓住按键。

    private void parentForm_Load(object sender, EventArgs e)
    {
        childForm frm2 = new childForm();
        frm2.KeyPress += frm2_KeyPress;
        frm2.Show();
    }
    
    void frm2_KeyPress(object sender, KeyPressEventArgs e)
    {
        //some codes here about what to do
    }
    

    希望能帮到你……

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-10
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-14
      • 1970-01-01
      相关资源
      最近更新 更多