Saturday, January 20, 2007

Intercepting the Arrow Keys in a Windows Forms Application

I have a Windows Form populated with a few controls. I want to let the user use the arrow keys to control some of the actions on the window. However, it seems like every time the user presses the arrow key, the controls (such as Button control) on the form receives the event and acts on it instead. How do I disable this behavior?

By default, special keys (such as Left, Right, Up, Down, etc) are filtered for focus management. That is to say, when you press the one of the arrow keys, Windows will automatically choose the next control on your form and set the focus on it. However, you can override this behavior by writing some code.

If your form has got no controls on it (or has controls that does not handle any keyboard inputs (such as the Panel control)), the easiest way would be to handle the KeyDown event of the form, like the following:

Private Sub Form1_KeyDown( _
   ByVal sender As Object, _
   ByVal e As System.Windows.Forms.KeyEventArgs) _
   Handles Me.KeyDown
        If e.KeyData = Keys.Up Or _
           e.KeyData = Keys.Down Or _
           e.KeyData = Keys.Left Or _
           e.KeyData = Keys.Right Then
            '---perform your own action---
            e.Handled = True
        End If
    End Sub

However, if the form contains controls that handles keyboard input (such as the TextBox and Button controls), then things get a little tricky.

Assuming you have some Button controls on your form and you want to disable the arrow keys having an effect on them. You need to do the following:

  1. Extend the Button control and override the IsInputKey function:

Public Class ExtendedButton
    Inherits Button
    Public Event ArrowClicked(ByVal key As Keys)

Protected Overrides Function IsInputKey( _
   ByVal key As Keys) As Boolean
        Select Case (key)
            Case Keys.Up, Keys.Down, _
               Keys.Left, Keys.Right
                RaiseEvent ArrowClicked(key)
                Return True
        End Select
        Return MyBase.IsInputKey(key)
    End Function
End Class

  1. Programmatically add the extended Button control to your form:

Private Sub Form1_Load( _
   ByVal sender As System.Object, _
   ByVal e As System.EventArgs) _
   Handles MyBase.Load

        Dim b1 As New ExtendedButton
        With b1
            .Text = "Button 1"
            .Location = New Point(10, 20)
            AddHandler .ArrowClicked, _
               AddressOf ArrowClicked
        End With

        Dim b2 As New ExtendedButton
        With b2
            .Text = "Button 2"
            .Location = New Point(100, 20)
            AddHandler .ArrowClicked, _
               AddressOf ArrowClicked
        End With
    End Sub

  1. Define the ArrowClicked event handler:

Public Sub ArrowClicked( _
   ByVal key As Windows.Forms.Keys)
        '---insert code here to do what
        ' you are supposed to do---
        Console.WriteLine("key pressed " & _
    End Sub

That’s it! When the user now presses one of the arrow keys, the ArrowClicked event will be fired. You can insert the code to do whatever you are supposed to do here, such as animating some actions on your form, etc.

Friday, January 19, 2007

Apple Confidential 2.0

As you are probably aware, I spend most of my time writing code and exploring new technologies happening in the Windows world. However, several years back I started venturing into the Mac as I was fascinated with the Mac OS X. However, my primary interest on the Mac was still pretty much constrained to using it as an end-user. As a result, I contributed to a few Mac consumer books, such as Mac OS X Unwired, Mac OS X Hacks, Mac OS X Panther Hacks, and Mac OS X Panther in a Nutshell, as well as several articles on MacDevCenter.

I have always been very interested in reading the success stories of companies, and I have a dozen of books on Microsoft, Apple, and Dell. Among all these books, my personal all-time favorite is still Apple Confidential 2.0 (updated edition of Apple Confidential). If you enjoy reading about how the Mac came about (or just anything about Steve Jobs and Steve Wozniak, and all others that played a role in shaping Apple), this book is a very captivating read. It covers Apple’s history since the beginning till the era of the iPod. As this book was published in 2004, it does miss out some of the important events in Apple’s history, such as the transition to Intel platform, the tremendous success of the iPod, and of course, the announcement of the iPhone. But all these do not make the book any less interesting. I especially like the sidebars that appear on almost every page, which provides little snippets of interesting information.

This book will give you a good explanation to the following questions:
  • Why did Apple kill the clones?

  • Heard of Newton? Why is it not around today?

  • How the design of iMac came around?

  • Who is the true father of the Macintosh?

Thursday, January 18, 2007

Programmatically Switch to Another Running Application/Process

In my Windows application, I want to be able to switch to another application running on my computer. For example, I want to switch to Internet Explorer and make it the active window. How do I do that?

To solve this problem, you need to first obtain the list of processes currently running on your system. You then need to find the required application/process to switch to and then make that window active.

First, import the following namespace:

using System.Diagnostics;

Then, declare the following functions from the user32.dll (yes, you will use P/Invoke to switch the current active window):

    public partial class Form1 : Form
           private static extern bool
           SetForegroundWindow(IntPtr hWnd);

           private static extern bool ShowWindowAsync(
           IntPtr hWnd, int nCmdShow);

Define the following constant:

        private const int SW_RESTORE = 9;
Assuming that you want to switch to IE, the following function will retrieve the list of processes running, look for IE, and then make it the active window:

        private void SwitchToIE()
            Process[] procs = Process.GetProcesses();
            if (procs.Length != 0)
                for (int i = 0; i < procs.Length; i++)
                        if (procs[i].MainModule.ModuleName ==
                            IntPtr hwnd =
                            ShowWindowAsync(hwnd, SW_RESTORE);
                MessageBox.Show("No process running");
               "Internet Explorer is not running");

Voila! If at least one instance of IE is running, you will be able to switch to it; else it will display the message “Internet Explorer is not running”.

Wednesday, January 17, 2007

How to find out the number of lines taken up in a TextBox control?

How do I find out the number of lines taken up in a TextBox control?

Before we discuss the solution, let's recap that the TextBox control supports multiline using the Multiline property. If you set it to True, then you can span your text input over multiple lines. It also exposes the Lines property (supported only on .NET framework but not .NET CF), where you can check how many lines are stored in the TextBox control. However, the Lines property only reports the number of lines separated by a carriage return character. Hence, if you have a single long line that spans more than the width of the TextBox control, it would still report that you have a single line in it.

To really count the number of lines in it, you have to use P/Invoke.

.NET CF Solution
Declare the functions as follows:

Public Class Form1
<Runtime.InteropServices.DllImport("coredll.dll")> _
Shared Function SendMessage( _

ByVal hwnd As IntPtr, ByVal msg As Integer, _
ByVal wParam As Integer, ByVal lParam As Integer) As Integer
End Function

<Runtime.InteropServices.DllImport("coredll.dll")> _
Shared Function GetCapture() As IntPtr
End Function

Then, declare the constant and variable:

Dim hnd As IntPtr

Finally, do this in your code:

TextBox1.Capture = True
hnd = GetCapture()
TextBox1.Capture = False
Dim linecount as Integer = SendMessage(hnd, EM_GETLINECOUNT, 0, 0)

.NET Solution
Declare the following function:

Public Class Form1
Private Declare Function SendMessageAsLong Lib "user32" _
Alias "SendMessageA" ( _
ByVal hWnd As Integer, ByVal wMsg As Integer, _
ByVal wParam As Integer, ByVal lParam As Integer) As Integer

Define the following constant:


Finally, do this in your code:

Dim linecount As Long = SendMessageAsLong(TextBox1.Handle, EM_GETLINECOUNT, 0, 0)

Do you want more information about a prospective babysitter? Searching for an old relative? A people finder website can often help in many ways.

How to programmatically cause your Pocket PC to vibrate

I have a Pocket PC Phone Edition device and I want to programmatically cause it to vibrate. How do I do that?

The easiest way would be to use the Smart Device Framework 2.0. The OpenNETCF's Smart Device Framework is an extension to the .NET Compact Framework (.NET CF) and it fills the gap between the full .NET Framework and its subset - .NET CF.

For Smartphones, you can use the Play() method in the OpenNETCF.WindowsMobile.Vibrate class to start the vibration. Unfortunately, this method only works for Smarthphones. For Pocket PC devices, you have to use the notification led to emulate vibration.

The following code shows how to cause your Pocket PC to vibrate for 0.5 second:

Dim vib As New OpenNETCF.WindowsCE.Notification.Led
'---start vibration---
vib.SetLedStatus(1, OpenNETCF.WindowsCE.Notification.Led.LedState.On)
'---stop vibration---
vib.SetLedStatus(1, OpenNETCF.WindowsCE.Notification.Led.LedState.Off)

The first parameter of the SetLedStatus() method takes in an integer representing the led number. You may need to trial-and-error to find the number that works correctly on your device.

Monday, January 15, 2007

Practical .NET 2.0 Networking Projects

I have an uncoming book to be released on the 29th of this month - Practical .NET 2.0 Networking Projects. This book demonstrates some of the key networking technologies that are being made easily accessible through .NET Framework 2.0. It discusses communication between wired machines and between networks and mobile devices. The book teaches you about the technologies by walking you through sample projects in a straightforward and direct way.
The book begins by discussing background theory so you'll get comfortable with the layout of the .NET Framework and Compact Framework from a networking perspective. Then you'll use the APIs within these frameworks to build a variety of cutting-edge networking applications that cover everything from Bluetooth and RFID communication to sockets programming and chat servers. You'll build working examples for each project, which you can also customize and use for your own purposes. The featured projects cover:
  • Basic introduction to network programming in .NET 2.0
  • Sockets programming
  • Serial communication
  • Bluetooth and GPS
  • Infrared networking to mobile devices
  • RFID

It is available for pre-order now at Check it out!

Windows Mobile Device Center (a.k.a. ActiveSync)

If you are a Pocket PC (Windows Mobile) user and have been syncing it with your Windows XP computer, you will be in for a surprise when you move to Windows Vista. In Windows Vista, ActiveSync is no longer supported. In place of ActiveSync is Windows Mobile Device Center, which enables you to set up new partnerships, synchronize content and manage music, pictures and video with any Windows Mobile 2003 or Windows Mobile 5.0 powered device. The Windows Mobile Device Center Beta is only supported on Windows Vista RC1 or later.

Applications Switching in Windows Vista

In the previous versions of Windows (XP, 2003, 2000, etc), you press Alt-Tab to switch between applications. One of the frustrations with using the Alt-Tab is that if you have a large number of applications open you have to cycle through each of them one-by-one; you can't simply click to select the application you want to switch to.With Vista, you have two choices:
  • Alt-Tab - You can cycle through all the open applications and click to select the application you want to switch to.
  • Windows-Tab - This will give you a 3-D view of all the open applications. You can also click to select the application to switch to. For this feature, you need to have the Aero Glass enabled.

Using Visual Studio 2005 in Windows Vista

If you are using Visual Studio 2005 in Windows Vista, be sure to update it with the following service packs (in the order shown):

Sunday, January 14, 2007

Building your own PC?

In the last 18 years, I have owned numerous computers and interestingly, of all the machines I have used, only one is factory built (the first PC I own). I still remember the excitement I had the first time I got a PC – that was a IBM-compatible XT (running the Intel 8088 chip), 640KB of memory with two disk drives – one 5.25” and the other 3.5”. Hard disk at that time was a luxury and I just could not afford one. And so I happily programmed on it and even partitioned part of the 640KB as a virtual drive to speed up the performance of the PC. After saving enough money two years later, I finally upgraded the PC to an AT (Advanced Technology) running the Intel 80286 chip. I brought the PC to an upgrade shop and changed the motherboard to an 80286 and added a 40MB (yes, you read it right!) Western Digital hard disk.

At that time, you can “low-level” format, as well as “high-level” format a hard disk. I am not sure what happened then, but after formatting the hard disk, it started making funny noises and stopped working. And so I had to lug the PC down to the repair shop again to change a new one. Fortunately, I managed to change a new one or else I had to folk out another USD$300 for a new hard disk. But that incident made me determined to learn more about the inner workings of my PC and I started to read more about the parts that goes into a PC. Along the way, I bought second-hand parts like casings, hard disks and motherboards and try to assemble them together. I learnt things the hard way – sometimes the parts don’t work together, or are of the wrong dimensions to fit into my casing. But learning through mistakes is the best way to learn. And eventually I was good enough to assemble PCs for friends and made some money to buy more computer books ;-)

Recalling my past experiences, if you want to learn more about the PC hardware you are using, I have the following suggestions:

* Pop into a local hardware shop and immerse in the tech-talk. Get yourself acquainted with the different jargons – ATX, S-ATA, Core 2 Duo, RAID, DDR2, ECC, etc. You may not understand everything the first time you encounter these terms, but trust me – after walking a few more shops you will have a good idea of what each term means.

* When in doubt, ask. Always ask the difference between variations of a product. For example, you can always ask the difference between a P-ATA and an S-ATA hard disk. The shop who is willing to do business with you will be delighted to share more information with you.

* Get a good book. After seeing and touching the hardware, it is always good to find a moment to recap what you have learnt and understand the theory behind it. In the early days, I was always very fascinated with hard disks and I thoroughly enjoyed the “The Hard Disk Survival Guide” by Mark Minasi. Today, I keep the “Building the Perfect PC” (1st and 2nd editions; written by Robert Thompson, Barbara Fritchman Thompson) by my side so that I can always refer to it whenever I need to. Robert and Barbara have done a good job sharing with you their experiences in building the perfect PC for different kinds of tasks. I highly recommend this book as it gives you various advices in choosing the best part for your PC so that you can avoid making the costly mistake yourself. I just wished the book was around when I first started computing.

And the final suggestion is, of course, get your hands dirty!

Tuesday, January 09, 2007

Performing Transactions in Windows Workflow

A transaction-oriented application is one of the common things that developers are tasked with handling, but that doesn't mean it's easy. Transactions are tricky thanks to tricky rollback conditions that must execute flawlessly. Find out why Windows Workflow can take the pain out of building transactions with a visual roadmap.

Input Validation

I demonstrate how to use the validation controls in ASP.NET, as well as how the validation controls have been improved in ASP.NET 2.0.

* Membership required to view the article.

Build Snippets with Code Snippet Editor for Visual Basic 2005

Want to create code snippets for Visual Studio 2005, but don't want to get your hands dirty? I show you how to do it by using the Code Snippet Editor for Visual Basic 2005, a shared source project developed by the Visual Basic developer community.

Building FTP Services Using .NET 2.0

.NET 2.0 provides two new managed classes for performing FTP accesses. With them, you can incorporate FTP into your applications easily. I show you how to perform the most common FTP functions using these two new classes.

Build Your Own Media Center PC, Part 2

Windows Media Center turns your ordinary PC into an all-in-one home entertainment center to watch and record TV programs, play DVDs, listen to music, share your digital photos, and more. In this second part of a two-part series, I show you how to assemble the PC and watch and record TV.

Monday, January 08, 2007

A good resource on Windows development tools

Windows Developer Power Tools: Turbocharge Windows Development with More Than 140 Free and Open Source Tools (Paperback)
by James Avery, Jim Holmes

I am currently reading this book and at close to 1300 pages it is a very comprehensive resource if you are a Windows developer. If you are a Visual Studio developer, then this book is for you as it contains a lot of coverage on .NET related tools and add-ons.

What I am reading now...

iWoz: From Computer Geek to Cult Icon: How I Invented the Personal Computer, Co-Founded Apple, and Had Fun Doing It (Hardcover)
by Steve Wozniak, Gina Smith

Wednesday, January 03, 2007

New Course on .NET 2.0

This month, I am launching a new course on .NET 2.0 (3 days). If your company/school is interested to get jumpstarted in key .NET 2.0 technologies, contact me at for a quote.

Here are the key topics covered:

1) Windows Forms 2.0
2) ASP.NET 2.0
3) ASP.NET AJAX Framework
4) Hands-on Projects
* Mesh-up - Using Google Maps with GPS
* AJAX-enabling an ASP.NET Web site
* Hardware Integration – Incorporating fingerprint recognition into your .NET applications
* Hardware Integration – Incorporating a webcam into your .NET applications