如何设置专注于表格?

时间:2012-09-17 12:52:41

标签: c# winforms

我正在尝试从用户获取输入的值并将其保存在char变量上,但问题是没有发生任何事情,我觉得问题出在Form Focus ,这个是代码,当我运行它时不会发生错误,但也没有任何反应。我做错了什么?

        char keyPressed;

        public FrmZigndSC()
        {
            InitializeComponent();
            this.Focus();
        }

        private void FrmZigndSC_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            keyPressed = e.KeyChar;

            LblResult.Text += Convert.ToString(keyPressed);
        }

6 个答案:

答案 0 :(得分:2)

您可以尝试使用此代码 - 基于KeyPressEventHandler

public FrmZigndSC()
{
       InitializeComponent();
       this.Focus();

       //Subscribe to event
       this.KeyPress += new KeyPressEventHandler(FrmZigndSC_KeyPress);
}


private void FrmZigndSC_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
        keyPressed = e.KeyChar;
        LblResult.Text += Convert.ToString(keyPressed);


        // Indicate the event is handled.
        e.Handled = true;
}

答案 1 :(得分:1)

我试图在一个空的小Windows Forms项目中重现它。没有Shown事件处理程序,此代码工作正常:

public partial class FrmZigndSC : Form
{
    public FrmZigndSC()
    {
        InitializeComponent();

        this.KeyPress += (s, e) => this.LblResult.Text += e.KeyChar.ToString();

        // this might be a solution, but i did not need it
        this.Shown += (s, e) => this.Activate();
    }
}

无论如何,您可以尝试使用this.Activate()并查看它是否有帮助。如果您在表单上有其他输入控件,例如文本框,请尝试将表单的KeyPreview属性设置为true。

答案 2 :(得分:1)

如果您想从应用程序的消息管道接收密钥通知,那么在这种情况下,转发元素的焦点会使架构变得脆弱。你不能保证你的应用程序中的其他形式可能会集中注意力,或者表格不会被吸收该事件的某些控件覆盖。你不能错过一个有焦点的形式,因为它是完全糟糕的用户体验设计(即使可以100%的工作方式实现,也不是很确定)。

可以做什么,而是声明从IMessageFilter派生的类:

public class MessageFilter : IMessageFilter
{
        const int WM_KEYDOWN = 0x100;
        const int WM_KEYUP = 0x101;

        public bool PreFilterMessage(ref Message m)
        {
            // Intercept KEY down message
            Keys keyCode = (Keys)(int)m.WParam & Keys.KeyCode;

            if ((m.Msg == WM_KEYDOWN)
            {
                 //get key pressed  

                 return true;
            }        
            else
            {
                return false;
            }


        }
}

注册之后,在你的应用程序中:

MessageFilter filter = new MessageFilter(); //init somewhere 


Application.AddMessageFilter(filter ); // add 

..... 

//on application end don't forget to remove it 
Application.RemoveMessageFilter(filter );

答案 3 :(得分:0)

使用FocusManager而不是this.Focus()可以做到这一点!

http://msdn.microsoft.com/en-us/library/system.windows.input.focusmanager.aspx

答案 4 :(得分:0)

我认为问题在于,当你的表单上有不同的控件来捕获压缩。我的控件上有一个带有DateTimePicker的问题。

尝试删除所有这些,然后尝试它,它会工作。从那时起再次添加控件以查看问题所在。

答案 5 :(得分:0)

您提供的代码对我来说很好。将启动页面设置为FrmZigndSC,然后重试。

相关问题