See the well-known sample from Petzold which does exatly that, posted many times on usenet..