Go Go Gnome
the website of Sander Kooijmans

Disable button click triggered by enter in Compact Framework 2.0

Posted: January 13, 2012
Last modified: December 21, 2020

Mobile devices do not have a mouse. When the user uses the touch screen to click on a button, then this click is translated to mouse events. This way existing software can still be used on a mobile device without a mouse.

When the mobile device has a barcode reader, then when a barcode is scanned, this barcode is offered to the application as if it was typed on a keyboard. And typically a key press for the enter key is added after the barcode.

But what happens if the user accidentally moved the focus from a text box to a button? If the user then scans a barcode, the key presses for the barcode are ignored, but the key press for the enter will cause a button click!

It turns out that preventing this button click is difficult in Compact Framework.

I finally found a solution in the article "SubClassing a Control Using Native Callbacks" at codeproject.com. Compact Framework offer the possibility for native code (like the Button class) to call managed code using a callback delegate. The article describes how to implement a callback delegate that is called when the mouse button is pressed or released.

The solution I came up with is to create a subclass of Button. When the mouse button is pressed a flag is set. The method OnClick() only handles the click if the flag is set and then clears the flag.

One minor problem was that pressing enter on the mobile device actually sent two mouse press events. The second event always has wparam = 0 and lparam = 0. When such an event is received I also clear the flag so that the following call to OnClick() does not handle the click.