Hi all,

How to set default focus on button in winform using C#?

Thanks and regards,

Swapnil.

Ah I see ok. You need to Implement the IMessageFilter in your form to catch key events and process them.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace KeyHooks
{
    public partial class Form1 : Form, IMessageFilter
    {
        const int WM_KEYDOWN = 0x100;
        const int WM_KEYUP = 0x101;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Application.AddMessageFilter(this);
        }

        public bool PreFilterMessage(ref Message msg)
        {
            Keys keyCode = (Keys)(int)msg.WParam & Keys.KeyCode;
            if (msg.Msg == WM_KEYDOWN && keyCode == Keys.Return)
            {
                DoButtonClick("You pressed return");
                return true;
            }
            return false;
        }

        private void Form1_Load()
        {
        
        }

        private void DoButtonClick(string message)
        {
            label1.Text = message;
        }
        
        private void button1_Click(object sender, EventArgs e)
        {
            DoButtonClick("you clicked me");
        }


    }
}
This article has been dead for over six months. Start a new discussion instead.