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");
        }


    }
}

We can do it by AcceptButton property of Form.

Thanks and regards,

Swapnil.

Ah very good, much simpler yes.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.