Click here to Skip to main content
15,907,497 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hi!!

I´m working on a WPF application. This app contains two projects(MainProject and UserControlProject).

I would want to achieve the following.

At UserControlProject I´ve a control that contains a TextBox. Each time this TextBox got the focus, a keyboard is shown on the screen. I´d like to enable/disable this keyboard on a Combobox included on a window from the MainProject.

How can I achieve it?

I´ve been looking for solutions like global variables. Am I on the right way?

Thanks for all.
Posted

1 solution

In .NET, there is no such concept as "global variable". And this is a good thing. Finally!

Now, your problem is simple and does not require anything "global" whatsoever. You simply need to handle the event System.Windows.UIElement.GotFocus or System.Windows.UIElement.GotKeyboardFocus:
http://msdn.microsoft.com/en-us/library/system.windows.uielement.gotfocus.aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.uielement.gotkeyboardfocus.aspx[^].

Suppose you don't want to handle it inside your custom control itself, but want to delegate it to whatever code using your control. In this case, you should define an event in your control and still handle the focusing event in a fixed way, invoking your public custom event. Something like this:
C#
public class MyControl : Control {
    
    TextBox myTextBox = new TextBox();
   
    //...

    public MyControl() {
        myTextBox.GotFocus += (sender, eventArgs) => {
            if (TextBoxFocused != null)
                TextBoxFocused.Invoke(this, new System.EventArgs()); // it will call the user-supplied event handlers
        };
        //...
    }

    public event System.EventHandler TextBoxFocused; // will be invoked via the anonymous handler shown above
 
} //class MyControl


I just want to warn you in advance: it you are using some virtual keyboard of your own, it will give you the following problem: it will grab the keyboard focus out of the text box control, so you would need to find a way to send keyboard events to a non-focused control, or, alternatively, prevent grabbing focus by having the virtual keyboard totally non-focusable yet shown on top (there is an "always-on-top" style). This is easier with Forms, could be more tricky if this is all WPF.

I depicted the ideas of resolution of the focusing problem, but it should be a matter of a separate question. First face the problem itself.

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900