eselk
eselk

Reputation: 6894

Application.OnKeyDown event for winforms?

Borland's VCL library has application wide events that let me do some global keystroke processing. Is there anything like this in .NET Winforms?

I have a Winforms app with about 10 forms so far, and unfortunately I didn't create a baseclass that all forms derive from (the process didn't seem as simple as it was in VCL) so I can't just add code to the base class. Unless it would be easy to add that now and quickly subclass the 10 existing forms?

What my end-user wants is a way to catch certain keystroke combinations entered in any field and replace them with other words. Like typing "so" would be replaced with "stack overflow".

Not looking for exact code or anything, just some ideas on general ways to handle this. So far I've thought of subclassing all forms, or subclassing all textbox controls, but not sure what other options there are? In VCL I would catch the global keydown event, check the active control, check the text in the control, and based on the text and the current selection I would replace as needed.

Upvotes: 0

Views: 173

Answers (1)

Rick Hodder
Rick Hodder

Reputation: 2252

To further Hans' suggestion, you might want to create a behavior class that has a method that matches the event handler signature of TextChanged, and holds the algorithm.

   public class AutoTextBehavior
    {
        public void TextChanged(object sender, EventArgs e)
        {
            Console.WriteLine("Text Changed");
        }
    }

Then you can hook to TextChanged of any of the input controls that you want to have this behavior. For example in the constructor of a form that has two textboxes (t1 and t2), you could put the following:

public class Form1 : Form
{
     AutoTextBehavior behavior = new AutoTextBehavior();

     public Form1()
     {
         InitializeComponent();
         this.t1.TextChanged += behavior.TextChanged;
         this.t2.TextChanged += behavior.TextChanged;
     }
...
}

Or you could make the controls instantiate their own behavior:

public class myApplicationTextbox : Textbox
{
   AutoTextBehavior behavior = new AutoTextBehavior();

         public myApplicationTextbox()
         {
             InitializeComponent();
             TextChanged += behavior.TextChanged;
         }
...
}

Upvotes: 1

Related Questions