Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find previous active control c#

Tags:

c#

.net

winforms

i am developing keyboard control, very simple embedded on a form. using sendkey class to perform char entry. to make this functional is required to know previous selected control.

like image 478
volody Avatar asked Oct 15 '25 16:10

volody


2 Answers

Something like the following should do the trick:

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

namespace DragDropTest
{
    public partial class LostFocusTestForm : Form
    {
        private Control _lastControl;

        public LostFocusTestForm()
        {
            InitializeComponent();

            TrapLostFocusOnChildControls(this.Controls);
        }
        private void finalTextBox_Enter(object sender, EventArgs e)
        {
            MessageBox.Show("From " + _lastControl.Name + " to " + this.ActiveControl.Name);
        }

        private void AllLostFocus(object sender, EventArgs e)
        {
            _lastControl = (Control)sender;
        }

        private void TrapLostFocusOnChildControls(Control.ControlCollection controls)
        {
            foreach (Control control in controls)
            {
                control.LostFocus += new EventHandler(AllLostFocus);

                Control.ControlCollection childControls = control.Controls;
                if (childControls != null)
                    TrapLostFocusOnChildControls(childControls);
            }
        }
    }
}
like image 162
Mark Bertenshaw Avatar answered Oct 17 '25 06:10

Mark Bertenshaw


Expanding on David's answer. This is how you can use the Enter event and a variable to store the last control:

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        Control lastControlEntered = null;

        public Form1()
        {
            InitializeComponent();

            foreach (Control c in Controls)
                if (!(c is Button)) c.Enter += new EventHandler(c_Enter);
        }

        void c_Enter(object sender, EventArgs e)
        {
            if (sender is Control)
                lastControlEntered = (Control)sender;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            label1.Text = lastControlEntered == null ? "No last control" : lastControlEntered.Name;
        }
    }
}

To run this code, add a few textboxes and other control to a Form in Visual Studio, and add a button and a label and attach the button's click handler to button1_Click. When you press the button, the last control you were in before pressing the button is displayed in the label. Edit this code to suit your needs.

like image 42
Mark Byers Avatar answered Oct 17 '25 05:10

Mark Byers