Getting Mouse Events in a Compact Framework TextBox

Yesterday I got a support request for the Smart Device Framework.  The user was after a seemingly simple behavior – they wanted to get a Click or MouseDown event for a TextBox is their Compact Framework application so they could select the full contents of the TextBox when a user tapped on it.

Of course on the desktop this is pretty simple, you’d just add a handler to the Click event and party on. Well, of course the Compact Framework can’t be that simple. The TextBox has no Click, MouseUp or MouseDown events. Thanks CF team. There are some published workarounds – one on CodeProject and one on MSDN – but they involve subclassing the underlying native control to get the WM_LBUTTONDOWN and WM_LBUTTONUP messages, and honestly that’s just not all that fun. Nothing like making your code look like C++ to kill readability.

For whatever reason (I can’t give a good one offhand) the TextBox2 in the Smart Device Framework also doesn’t give any of the mouse events, *but* it does offer a real easy way to add them since it does allow simply overriding of the WndProc. Basically you just have to create a new derived control like this:

    public class ClickableTextBox : TextBox2
    {
        public event EventHandler MouseDown;

        protected override void WndProc(ref Microsoft.WindowsCE.Forms.Message m)
        {
            base.WndProc(ref m);

            switch ((WM)m.Msg)
            {
                // do this *after* the base so it can do the focus, etc. for us
                case WM.LBUTTONDOWN:
                    var handler = MouseDown;
                    if (handler != null) handler(this, EventArgs.Empty);
                    break;
            }
        }
    }

And then using it becomes as simple as this:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            textBox2.Text = "lorem ipsum";
            textBox2.MouseDown += new EventHandler(textBox2_MouseDown);
        }

        void textBox2_MouseDown(object sender, EventArgs e)
        {
            textBox2.SelectAll();
        }
    }

2 Comments

Leave a Reply