Brendan Enrick

Daily Software Development

Handling Keyboard Input in Silverlight

Keyboard input is one of the most important aspects of truly rich programming environments. I understand that one usually identifies a rich interface as one which can interacted with visually. This interaction feels more natural than keyboard interaction. The mouse allows the user to feel as if he can truly manipulate the environment in which he is working. One cannot, however, ignore the importance of the keyboard in any environment expecting to be able to perform much meaningful work. Again I'll be talking about some code that I wrote many months ago. Sorry for being so late mentioning this stuff. I just need to find more time in the day. I'll find that 25th hour eventually.

Handling keyboard input with Silverlight 2.0 is very easy. In Silverlight 1.1 there wasn't even an enumeration for the keys. Now that it is included one simply has to wire up some handlers for keyboard input. For my purposes I've been using it for gaming, but others could be using this for almost anything. Keep that in mind and use this by adapting it to your needs at the time.

Initializing the key up and key down event handlers is very easy. You just call a couple of lines like these and create a couple of empty methods which we will write later, so we start with this.

this.KeyDown += new KeyEventHandler(Page_KeyDown);
this.KeyUp += new KeyEventHandler(Page_KeyUp);

This will tie these events to the page. If you want to tie them to another element, use its x:Name instead of this. I like to have a more central method for handling keyboard events, so I'll create a method for handling the keys and I will call that method in my event handlers.

private void Page_KeyUp(object sender, KeyEventArgs e)
    HandleKey(e.Key, false);

private void Page_KeyDown(object sender, KeyEventArgs e)
    HandleKey(e.Key, true);

Notice that the KeyEventArgs parameter, e, has data about the event, so if you needed more information from it you could obtain it and pass it to HandleKey also. I prefer this to having too much logic directly in my event handlers. The boolean value I am passing is just letting me know whether the key is being pressed or released.

In a game it is important to know the state of the keyboard at any given time. Since Silverlight currently doesn't tell me if a key is being pressed I use this system to allow me to detect a held key as well as when keys are pressed and released. If you're doing something similar then you will probably use something similar to this.

private void HandleKey(Key key, bool isDown)
    switch (key)
        case Key.Escape:
            if (isDown) EndGame(Enums.EndGameType.Quit);
        case Key.Up:
        case Key.W:
            _upIsPressed = isDown;
        case Key.Down:
        case Key.S:
            _downIsPressed = isDown;
        case Key.Left:
        case Key.A:
            _leftIsPressed = isDown;
        case Key.Right:
        case Key.D:
            _rightIsPressed = isDown;

By knowing the state of the keyboard at any given time, I can allow my silverlight game loop to know what keys are currently being pressed and respond to them. This allows the game to play along as the user uses keyboard input to interact with the game. These same ideas and code can be modified easily to work with nearly anything. This is why I make sure that the code snippets I show are quite simple. It makes them more easily adapted to a variety of solutions.

I hope everyone is enjoying Silverlight. Make sure you listen to the Silverlight Song. It is a riot.

Creating a Game Loop Using Silverlight

I've been playing with silverlight as a gaming platform for a few months now. I've not published or released anything I've done yet, but I expect I will at some point. I am not much of a game developer really, and I've been hacking things together as best I can. I, like many other developers, have always found game development to be quite interesting. So for now I'll talk about how to create a game loop.

What are Game Loops Used For?

In most games you need to have some control over the passing of time. You always need to be constantly able to respond to user input without stopping the game waiting for this user interaction. It allows you an opportunity to have the game move with or without the player. This loop will allow you to have computer-controlled enemies and neutrals decide how to act and to take these actions.

How to Create a Game Loop

I've found two ways I like for creating game loops. I am sure that there are plenty of others. If you wanted to, you could also wrap these up into classes so it abstracts the ugly details of creating a game loop. Perhaps a class which just lets you create a new instance of the game loop class and lets you assign a method for handling the looping.

Since I am just trying to show the simple how to of it, I'll leave out the class and leave that as an exercise for the reader. The two ways I know of for creating game loops are to use a System.Windows.Threading.DispatchTimer or a System.Windows.Media.Animation.Storyboard. I prefer the timer simply because it feels more hacky to use a storyboard. This just feels more like it should be some sort of a timer managing this, so it's what I like to use.


// Initialize the Main Game Loop

_timer = new DispatcherTimer();

_timer.Interval = new TimeSpan(100);

_timer.Tick += new EventHandler(MainGameLoop);


What we've done here is just created this DispatchTimer and told it to run fire the MainGameLoop method every time the timer ticks. The timer has an interval set to 10 miliseconds in this example, so our loop should execute 100 times every second.

private void MainGameLoop(object sender, EventArgs e)


// ....

// Do Stuff Here For the Game

// ....


Again another exercise for the reader is to create a game by filling in that MainGameLoop as well as other portions of the code. I plan on fleshing out some games if I ever get enough free time to work on it. I'll be back to post some more stuff. I expect it will be more complicated that this. I just don't want to post my whole game yet. It will be released eventually. I am not making Duke Nukem Forever, so you can expect my game will actually release at some point.

Programming Information Titled Security

Disclaimer: This post is not about security.

Is anyone else bothered by Information titled with the word security? Let me explain what it is I am referring to. I will see an article, a blog post, or a section on a web site which claims to be about "security." I will of course be quite interested when I see this, because I think security is very important when programming. One must be careful to not leave easy ways for people to exploit one's code. I think this is an important issue and it tends to be overlooked by many software writers.

The problem is that most of the time the writing I find about "security" is in actuality information about "authentication." I understand that "security" is a word which certainly can be used to describe authentication, roles, permissions, etc. I just dislike it when it is used in such a way when talking to programmers. Since it is the best word to describe the type of security which is preventing people from exploiting the code. Preventing attacks on a system is a very important aspect of programming, and it seems to be overlooked on the Internet.

I wish people would stop titling articles, book chapters, and whatever else as "security" when it is really just "authentication."

Anyone else run into any similar situations?

Enabling Mixed Mode Authentication in SQL Server

I recently needed to enable Mixed Mode Authentication on a SQL Server instance, so I will demonstrate how to go about setting this up. It is a pretty easy process, but I figure I'll document it nicely here. Perhaps I will come back to this later to reference this. Who knows?

First you will need to connect to the SQL Server instance using SQL Server Management Studio.


Once you've connected to the SQL Server you will need to get to the properties window for the server. To do this you can right click on the SQL Server in the Object Explorer window and it will bring up a context menu.


Now that you've got the properties window open, select the Security section and choose the SQL Server and Windows Authentication Mode radio button.


After clicking OK, you will receive a message informing you of the need to restart the Server before the changes take affect.


Now just right click on the server in the object explorer again and select restart from the context menu and the services for the server will restart.


Congratulations you're done.

Change SQL Server Instance for Visual Studio Database Project

While installing SQL Server 2005 recently I ran into some difficulty. I use database projects from Visual Studio 2005 Team Edition for Database Professionals. I use Visual Studio 2008 with them now, and I recently made a mistake while using one of these projects. When I ran this project my default instance of SQL Server was not listed, so I figured I would connect it to the SQL Express. BIG MISTAKE. After installing SQL Server and getting it working correctly I removed SQL Server Express, and now the real fun begins. The database project no longer loads.

So I try removing and adding the project in my solution figuring it might prompt me for the database instance again. No luck. So I decide to ask around a bit. One forum got me a nice response. It explained how to make the change as well as linking to this MSDN article.

To make this change you just have to alter some settings in Visual Studio. Start by navigating to the Tools menu and choose Options.


Once you've opened the Options menu, navigate to the Database Tools section and pick Design-time Validation Database. This is the information for the database used by Visual Studio for database projects. Change the SQL Server Instance Name to whatever the name of the local database is.


I made the bad assumption of assuming that the project is what connects to the server instead of Visual Studio. I checked everywhere in settings for the project, but it slipped my mind that Visual Studio would be what would contain that setting.

As one final note I will say Googling sucks when you're looking for information about "Visual Studio 2005 Team Edition for Database Professionals". Ah what a great name guys.....