When I started writing this article, I decided that my CalcPad example was still just a bit lame. So I completely revised it again for this article. If you saw it before, you'll hardly recognize it as the same program.
The problem with writing a calculator program is making sure that the right thing happens when the keys are pressed. What happens, for example, if the equal key is pressed several times in succession? How do you program a chain calculation? (2 times 3 times 4) What if an operation key (multiply or add, for example) is pressed more than once?
Version 1 used a lot of internal flags to try to control the processing. I should have known better! It never did work right (Thanks to all the readers who let me know about that!) and it was waaaay complicated.
Version 2 was my first 'bright idea'. Instead of using flags, I used a VB.NET Queue object to maintain control over the operators and the numbers. Then the program can simply (?) Enqueue or Dequeue operators and numbers. It worked a lot better and the logic was much more straightforward ... and shorter. (Always a good sign that you're on the right track.) For the curious, here's a link to the source code for my second version.
But when I started writing this article, I ran into a few more cases where it just didn't do exactly the right thing in testing. So as I worked on finding and fixing the bugs, I made the decision to try 'bright idea' number two: program it as a sort of "Finite State Machine". I realized that the calculator was always in one of four "states" and that the program could be based around that.
Before ...
- the first number is entered
- the operation key is pressed
- the second number is entered
- the equal key is pressed
I introduced a new variable (named, naturally, State) and based the entire rest of the program on the value of that variable (it's zero based in the program code).
As nearly as I can tell (In all of a half hour's testing. You wouldn't believe how long it takes to create one of these articles and I have a deadline!) my program behaves exactly like the Windows calculator this time. If you find that it doesn't, let me know. The source for the actual calculator is the same in all of the downloadable examples.
And speaking of downloadable examples, to download a VB.NET 1.X and VB.NET 2005 CalcPad control project, Click Here!

