May 042010
 

So, I guess I’ll give this tutorial thing a try.  I’ll begin with something simple.

Let’s learn about Extension Methods in C#!

Extension Methods were introduced in C# version 3.0 (C# Version 3.0 Specification).  Extension methods allow you to add or “extend-to” a pre-existing class a method of some sort.  This is particularly useful when you wish extend a method to a type that is defined in C# (or something closed source) without having to create another class and derive another type.

The format is as follows:

public static void ExtensionMethod(this extensiontype var, type additionalvar1, type additionalvar2, .....)
{
    //Do something...
}

Ideally, you might wish to encapsulate these extension methods in their own class.  Perhaps even a class that only contains extensions for the particular type you’re extending:

public static class SomeTypeExtensions
{
    public static void ExtensionMethod(this extensiontype var, type additionalvar1, type additionalvar2, .....)
    {
        //Do something...
    }
}

Furthermore, you could encapsulate the multitude of extension classes you create into their own namespace and optionally include the use of the extensions on a class to class and/or file to file basis in the using statements.  I’ll let you decide on that at your own discretion.  I like to follow this convention in my projects where I need to use extensions:

namespace Extensions
{
    public static class SomeTypeExtensions
    {
        public static void ExtensionMethod(this extensiontype var, type additionalvar1, type additionalvar2, .....)
        {
            //Do something...
        }
    }
}

It’s important to note that the class containing your extension method must be static and the method you are extending must also be static.  This is a requirement for extensions methods.

OK.  Now that we have the appropriate syntax in our heads for defining an extension method, let’s put what we’ve learned to use.  Let’s define a simple extension to the int type that allows us to print the value of the int to stdout:

namespace Extensions
{
    public static class IntExtensions
    {
        public static void PrintInt(this int integer)
        {
            //Print the integer value for the int object caller
            //and a newline
            Console.Write(integer.ToString() + '\n');
        }
    }
}

You can choose optionally which classes you wish to implement this extension based on the namespace where it lives.  If you have encapsulated the class in an ‘Extensions‘ namespace like I suggested earlier, then you can simply add it among the using statements of the classes you wish to have access to your extensions:

using Extensions;

Once a class has access to your extension you may call the extension method on any variable of the type you provided an extension for:

int number = 5;
number.PrintInt();

The output to the console will look like this:

ExtensionsExample1Output

It doesn’t get much straightforward than that.  If you wish to try out the code explained above here is a link to download the Visual Studio Project (requires Visual Studio 2008. Though, it may work with Visual C# 2008 Express or 2010 Express which are free.  I haven’t tested it.  You’re welcome to.):

Example1.zip

I have taken the time to create another, more advanced, example using the Microsoft.Xna.Framework (this requires XNA 3.1).  In the second example we are modifying a Texture2D object to extend a draw method to it.  The end result is a sand texture stretched across the game window.  Here’s a link to the second example project:

Example2.zip

For more guidance and examples you can consult the C# Programming Guide for Extension Methods at MSDN where they provide the general syntax and usage as well as recommendations for when extensions should and should not be implemented.

Hope this was helpful.  Thanks for reading!

Sources:

C# Version 3.0 Specification
(http://msdn.microsoft.com/en-us/library/ms364047%28VS.80%29.aspx)
Extension Methods, C# Programming Guide
(http://msdn.microsoft.com/en-us/library/bb383977.aspx)
Sand Texture Graphic for Example 2
(http://mayang.com/textures/Nature/images/Sand/sahara_sand_patterns_220511.JPG)
Oct 082009
 

It’s been a while since I’ve posted anything.  I actually managed to get my first Win32 window up and running some time last week.  But, this weekend I made a trip out to Las Vegas, NV with the girlfriend (Jenn) to see the Beatles Love Cirque du Soleil show at the Mirage.  Without an internet connection, I didn’t have a chance to update the blog.  Let me begin this post by saying that the Love show was worth the 4.5 hour drive out to Vegas.  Jenn and I had an awesome weekend, and I would recommend that show to everyone, Beatles fans or not.  Now… Let’s get to business.

So this week was quite the learning experience for myself.

I learned about the <windows.h> and <windowsx.h> headers and the WIN32_LEAN_AND_MEAN definition.

I learned about the following structures:

  • PAINTSTRUCT
    • Contains information that can be used to paint the client area of a window.
  • HDC (Couldn't find a reliable description on MSDN... sorry)
  • WNDCLASSEX
    • Contains window class information.
  • HWND
  • MSG
    • Contains message information from a thread’s message queue.

I learned about the following Win32 functions:

*It should be noted that a large amount of the windows functions mentioned are macros that were possibly set in place to make the function name more pleasing to the eyes.  The majority of them are simply defined as follows:
#define RegisterClassEx  RegisterClassExA

So, don’t be surprised if you look them up and find a simple define. Just go to the function definition that the macro is set in place for.

The main focus of the lesson was getting a Win32 window up and running.  And, as expected, the end result was that I had a pretty plain window similar to how most windows would look that belong to a Win32 program (Not a big surprise…)

One of the important things that was covered was WinMain as it is the main entry point into the program (though I’m pretty sure I mentioned its importance in a previous post). WinMain acts as the main entry point into a Win32 program just like main is the main entry point to a Win32 console program.

Some other important concepts of this particular segment of the book included defining your Window Class as a WndClassEx object and initializing window attributes like styles, the large and small icon used, the brush color to be painted on the background, and the mouse cursor to be used. While some of the attributes aren’t necessarily that important for anything more that aesthetics, there are two that should be given more consideration. The Window Class Name, and Window Procedure Callback Function are both very important.

The Window Class Name is the unique name that you give your Window Class to distinguish it from other window classes that may exist in your project. This attribute uniquely defines your window class and the operating system will refer to this class name to reference this particular window class type once it is set.

The second of the two important attributes is the Window Procedure callback function. This particular function is defined by you for your window and is called on your window’s behalf to process any messages that are created for your particular window class. Messages are instructions that are sent back and forth between the operating system and processes that are running on the operating system.

So following declaration and initialization of your window class, the next step is register the window class using the function RegisterClassEx (refer to the above links to function definitions). Once your window class has been registered you can proceed to create a window.

To actually create the window using your window class definition, you will have to utilize the function CreateWindowEx. This in itself is nothing more than a simple function call (read the above for a function definition). This will do nothing more than create a window, and without main game/program loop the process will draw the window for a split second then exit because there is no more processing to be done. The next step is to define a game loop where all of your message and general game processing can be done at every cycle iteration.

The simplest way to define your main game loop (or program loop if you aren’t writing a game) is to check for messages in a while loop. The basic concept is, “while there are messages to be processed, continue iterating through the loop processing messages.” Once there are no messages coming into your process, for example if the process is exited, the while loop will terminate and your program, in turn, will terminate.

And that is that.  That sums up what I’ve learned so far about Win32 programming.  I know I’ve covered a lot, and much of this might be over your head because this is new material. But this is about as far in depth as I’d like to go with a simple blog post. I know that more specific information might be more useful, but I thought that would be better left for a nicely written up and documented tutorial. For now, it is my hope that anyone reading this will survive using the links I have provided for each of the above functions and structures and use this blog entry as momentum to explore some of these concepts on their own.

Be sure to check back in the future. I will, most assuredly, want to encapsulate all I’ve learned in my travels into more helpful tutorials. But I can’t yet teach until I have learned. So bear with me and give me some time and don’t forget to check back frequently. Thanks for reading!

Sources:

Win32 structures and function references content originally found on: http://msdn.microsoft.com

Concepts and source code content originally found in “Tricks of the Windows Game Programming Gurus : Fundamentals of 2D and 3D Game Programming” by Andre Lamothe

The concepts found in this post are originally from the source file Demo2_3.cpp from the above book.

Source code for the book examples can be found here.