Tag: .NET

Using SDL2-C# to Capture Text Input

A common feature of applications and video games is to allow the player to input text for various reasons. Maybe we want to allow the player to input their character’s name in an RPG, name a city in SimCity, or type a chat message to a friend in online. Using SDL2, we can take advantage of its built-in text processing system which abstracts much of the operating system event handles and character encoding mechanisms.

On consoles such as Xbox and Playstation, text input is rather simplistic and limited to visual keypads that you select via the controller. On a PC, we have the full range of widely varying keyboards from English and Spanish to Russian and Japanese. If we want our game or application to attract users on an international scale, it’s probably in your best interest to learn here and now how to use SDL2 to accomplish this goal.

At first glance, it probably seems simple to process text input. If the user presses the ‘A’ key on the keyboard, the OS will send an event that the keyboard was just pressed, the key was ‘A’, and no modifier keys were pressed (CAPS, SHIFT, CTRL, ALT, etc…). That’s it, right? Unfortunately, there are a ton of languages on this planet, and some of them have thousands of characters in them. People who type in those languages most certainly do not have thousand-letter keyboards or entire walls of their houses dedicated as a giant keyboard. This basically means that some characters will require multiple key presses just to process. Fortunately, SDL2 handles all of this for us and simply sends us a byte array with the results.

Among SDL2’s event processing, the structure we are interested in is SDL_TextInputEvent. This event is sent through the SDL2 event processing chain whenever text is input. I have personally seen this trigger from both physical keyboards and the Windows virtual on-screen keyboard. I am sure that there are other ways to trigger this event as well. Using this event, we can get the character information that was input by the user. Here are the fields of the C-style structure that we can use:

UInt32     type          The type of the event
UInt32     timestamp     The time that the event occurred
UInt32     windowID      The ID of the window that has focus, if any
char       text          The null-terminated, UTF-8 encoded input text

After determining that this is an SDL_TextInputEvent by checking the type field, we are most interested in the text field. That field is a pointer to a character array which is encoded using the UTF-8 scheme. In my most recent cases, I was using a C# wrapper around the SDL2 library named SDL2-CS. Because C# runs in a managed, garbage collected runtime, it’s a bit tricky to get the text input from C into C# through the .NET marshaller, but here’s how to do it.

// the character array from the C-struct is of length 32
// char types are 8-bit in C, but 16-bit in C#, so we use a byte (8-bit) here
byte[] rawBytes = new byte[SDL2.SDL.SDL_TEXTINPUTEVENT_TEXT_SIZE];
Read more

Creating a Professional ToolStrip in Windows Forms Part 2

In my previous post, I explained how to create the basic UI elements of a simple Windows Forms application with a nice looking vertical ToolStrip menu to host buttons and labels without ever leaving the Designer. In this post, I’ll explain how to wire up some events, load in some UserControl objects, and add a custom rendering method to style our MouseClick events on the ToolStrip buttons. We’ll begin by opening the project from our previous post. (seen here)


  • Microsoft Visual Studio 2008 (or 2005, but I wrote this using 2008)
  • .NET Framework 3.5 (or 2.0, but I wrote this using 3.5)
  • Basic x,y coordinate knowledge to draw and position rectangles
  • Intermediate knowledge of C# and Windows Forms
    • Inheritance and overrides
    • Event handling

Step 1 – Create a Custom Rendering Class

  • Right click on the Project in the Solution Explorer, Add –> New Item… –> Class (.cs).
  • Name this class customRenderer.cs and click OK.

This class is going to inherit from ToolStripProfessionalRenderer so that we can override some of the rendering methods and make them do whatever we want. In this case, however, we will only be overriding the OnRenderButtonBackground method.

public class customRenderer : ToolStripProfessionalRenderer
    protected override void OnRenderButtonBackground(ToolStripItemRenderEventArgs e)

By overriding this method, we can change the behavior of how backgrounds are rendered. Some conditions will need to be applied in order to enforce that custom rendering only occurs on ToolStripButton objects and only when the objects are in a Checked state. Read through the comments in the next code block in order to understand some of the sections.

public class customRenderer : ToolStripProfessionalRenderer
    protected override void OnRenderButtonBackground(ToolStripItemRenderEventArgs e)
        // check if the object being rendered is actually a ToolStripButton
        if (e.Item is ToolStripButton)
            ToolStripButton button = e.Item as ToolStripButton;

            // only render checked items differently
            if (button.Checked)
                // fill the entire button with a color (will be used as a border)
                int buttonHeight = button.Size.Height;
                int buttonWidth = button.Size.Width;
                Rectangle buttonFill = new Rectangle(Point.Empty, new Size(buttonWidth, buttonHeight));
                e.Graphics.FillRectangle(Brushes.SteelBlue, buttonFill);

                // fill the entire button offset by 1,1 and height/width subtracted by 2 used as the fill color
                int backgroundHeight = button.Size.Height - 2;
                int backgroundWidth = button.Size.Width - 2;
                Rectangle background = new Rectangle(1, 1, backgroundWidth, backgroundHeight);
                e.Graphics.FillRectangle(Brushes.LightSkyBlue, background);
            // if this button is not checked, use the normal render event
        // if this object is not a ToolStripButton, use the normal render event

Take a few minutes to read through the above block of code in order to fully understand what’s happening. Follow the bullets below for an overview:

  • When Windows renders the button background on a ToolStrip, this overridden method will be called instead.
  • Only use our custom render code if the item is a ToolStripButton object.
  • Only use our custom render code if the ToolStripButton has its Checked property set to True.
  • Now, two different rectangles are going to be created and filled in order to achieve a 1 pixel border color that differs from the body color of the rendered button.
Read more

Creating a Professional ToolStrip in Windows Forms

Ever wanted to create a professional looking menu in your Windows Forms applications complete with big buttons, nice mouse over effects, and images? Well, look no further. In this post, I’ll show you how to implement a graphical ToolStrip menu to navigate through a Single Document Interface (SDI). You’ll notice that the finished interface is rather similar to Spybot – Search and Destroy. Keep in mind that the following example is rather simple and leaves a lot of room for expansion.


  • Microsoft Visual Studio 2008 (or 2005, but I wrote this using 2008)
  • .NET Framework 3.5 (or 2.0, but I wrote this using 3.5)
  • Beginner’s Knowledge Windows Forms

Step 1 – Create the Form Shell to Host the Menu

  • Create a new Windows Forms Application Project.
  • Select Form1 and adjust it’s size in the Properties Window to 964,600 (the exact size isn’t important, but you want to leave room for other controls once the menu is operational).

Step 2 – Add the Menus

  • From the Toolbox:
    • Drag in a MenuStrip and snap it to the top of Form1 by either dragging it until the blue line snaps to the top of the form, or drop it in Form1 and set the MenuStrip object’s Dock property to Top.
    • Drag in a TableLayoutPanel to the center of the form.
      • From the submenu that pops up when you drop in the TableLayoutPanel, click “Remove Last Row.”
      • Set this new Container’s Dock property to Fill.
      • From the Toolbox, drag in a ToolStrip and drop it into the left column of the new TableLayoutPanel.
      • Click the “…” button in the Property Window for this new control’s Columns property.
      • Set Column1 width to absolute 115px and Column2 width to relative 100%.
    • Drag a ToolStrip into the left column (Column1).
      • Set its Dock property to Fill.
      • Set its LayoutStyle property to VerticalStackWithOverflow. This will cause contents to stack top to bottom.
      • Set its GripStyle property to Hidden. This is only a matter of preference.
      • Set its Padding property to 5,5,5,5. This will give space on all sides for its contents.
      • Set its ImageScalingSize property to 35, 35. This will force images on Buttons to scale to 35px by 35px.

Step 3 – Add Content to the Menus

  • Using the “Add New Item” drop down in the ToolStrip:
    • Add a Label (menu section title).
    • Add two Buttons (menu section content).
    • Add a Label (menu section title).
    • Add three Buttons (menu section content).
  • While holding control, select each Button on the ToolStrip:
    • Set their DisplayStyle property to ImageAndText. This will cause a caption to be added to the Button in addition to an image.
    • Set their TextImageRelation property to ImageAboveText. This will cause the caption to be below the Button’s image.
    • Set their CheckOnClick property to True. This will cause the button to display as pressed or checked when clicked a single time. We will make the check state mutually exclusive for all buttons on the ToolStrip so that only one button can be checked at any given time to enforce SDI behavior.
Read more