Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event which occurs when form is focused

Tags:

c#

.net

winforms

I have two forms first is frmBase and second is frmBalloon.I alter the focus of both forms that first frmBase is shown then frmBalloon is shown(frmBase is not visible)and then again frmBase is shown.Now I have need of event that occurs first frmBase loads and then again when it shows after frmBalloon becomes not visible.

So I have need of event that occurs when form becomes focused.......

like image 214
Harikrishna Avatar asked Dec 30 '09 09:12

Harikrishna


1 Answers

Is Form.Activated what you're after?

My reason for suggesting this rather than GotFocus is that the form itself doesn't get focus if the focus changes from one form to a control on a different form. Here's a sample app:

using System;
using System.Drawing;
using System.Windows.Forms;

class Test
{
    static void Main()
    {

        TextBox tb = new TextBox();
        Button button = new Button
        {
            Location = new Point(0, 30),
            Text = "New form"
        };
        button.Click += (sender, args) =>
        {
            string name = tb.Text;
            Form f = new Form();
            f.Controls.Add(new Label { Text = name });
            f.Activated += (s, a) => Console.WriteLine("Activated: " + name);
            f.GotFocus += (s, a) => Console.WriteLine("GotFocus: " + name);
            f.Show();
            f.Controls.Add(new TextBox { Location = new Point(0, 30) });
        };

        Form master = new Form { Controls = { tb, button } };
        Application.Run(master);
    }
}

(Build this as a console app - that's where the output goes.)

Put some name in the text box and click "new form" - then do it again. Now click between the text boxes on the new form - you'll see the Activated event is getting fired, but not GotFocus.

like image 191
Jon Skeet Avatar answered Sep 21 '22 05:09

Jon Skeet