简体   繁体   English

在C#中动态创建Winform的Keypress事件

[英]Keypress event for dynamically created winform in C#

I'm creating a windows form at run-time. 我在运行时创建一个Windows窗体。 Now i want the Key-press event to be triggered for the dynamically created form. 现在,我希望为动态创建的表单触发按键事件。 How do i create/bind the event to newly/dynamically created windows form in C#. 如何在C#中将事件创建/绑定到新的/动态创建的Windows窗体。

Thanks, 谢谢,

Try This. 尝试这个。

Form dynamicForm = new Form();

dynamicForm.KeyPress += new KeyEventHandler(onkeyPress);    


 void onkeyPress(object sender, KeyEventArgs e)
 {
        Console.WriteLine("test");
 }

If we take a text box its like this. 如果我们采用这样的文本框。

    private void Form1_Load(object sender, EventArgs e)
    {
        TextBox myTextBox = new TextBox();
        myTextBox.KeyPress += new KeyPressEventHandler(myTextBox_KeyPress);

        this.Controls.Add(myTextBox);
    }

    void myTextBox_KeyPress(object sender, KeyPressEventArgs e)
    {
        //Do Key press event work here
    }

UPDATE 更新

Make sure that the focus should be on Form2 . 确保焦点应放在Form2

Make sure the forms KeyPreview Property is set to true, that way it will see the keystrokes. 确保窗体KeyPreview属性设置为true,这样它将看到击键。

From above link: 从上面的链接:

When this property is set to true, the form will receive all KeyPress, KeyDown, and KeyUp events. 当此属性设置为true时,表单将接收所有KeyPress,KeyDown和KeyUp事件。 After the form's event handlers have completed processing the keystroke, the keystroke is then assigned to the control with focus. 窗体的事件处理程序完成对击键的处理后,然后将击键分配给具有焦点的控件。 For example, if the KeyPreview property is set to true and the currently selected control is a TextBox, after the keystroke is handled by the event handlers of the form the TextBox control will receive the key that was pressed. 例如,如果KeyPreview属性设置为true,并且当前选定的控件是TextBox,则在通过窗体的事件处理程序处理了击键之后,TextBox控件将接收到按下的键。 To handle keyboard events only at the form level and not allow controls to receive keyboard events, set the KeyPressEventArgs.Handled property in your form's KeyPress event handler to true. 若要仅在窗体级别处理键盘事件,并且不允许控件接收键盘事件,请将窗体的KeyPress事件处理程序中的KeyPressEventArgs.Handled属性设置为true。

So you will want to do something like this: 因此,您将需要执行以下操作:

public partial class Form1 : Form
{
    Form2 f2;
    public Form1()
    {
        InitializeComponent();
        KeyPreview = true;
        KeyDown += Form1_KeyDown;
    }

    void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if(e.Control)
        {
            switch(e.KeyCode)
            {
                case Keys.C:
                    MessageBox.Show("Cntrl C");
                    break;
                case Keys.V:
                    MessageBox.Show("Cntrl V");
                    break;
                default:
                    break;
            }
        }
    }
}

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

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