Archive for the ‘C#’ Category

Handling events from within a ControlTemplate in WPF

Here’s an interesting one that had me stumped for a few hours.

Following on from my previous post, where I explained how to create a ControlTemplate to style a TextBox in WPF, I’ve got an object, TextEntryBox, which dervies from a TextBox (it provides some custom event handlers when text is entered, but to all intents and purposes, it’s a regular TextBox).

I wanted to style my TextEntryBox, this time including a button within my ControlTemplate (this will eventually toggle an on-screen keyboard pop-up, but that’s another blog post!). I came up with this:
Read the rest of this entry »

Tags: , , , , , , , , , , ,

1 Comment


How to create a ControlTemplate for a WPF TextBox

This is a short post, but has one specific piece of information I want to keep.

Q: If you want to create a ControlTemplate to provide a custom style for a TextBox, how do you specify where the text goes when it’s used in WPF?

A: The answer was hidden in the depths of the MSDN Documentation. You have to include a <ScrollViewer> within your ControlTemplate with an x:Name value of “PART_ContentHost”.

Here’s a noddy example:


Tags: , , , , , , , , , ,

No Comments


C#’s Null-Coalescing (??) Operator

Although I’ve always been a big fan of the ternary operator, kudos goes to the Refactoriser (you know who you are!) for pointing me in the direction of an even more effective way of obfsuca^H^H^H tidying up my code; the ?? operator.

The null-coalescing operator (to call it by its more catchy name) allows you to provide an alternative value in the event that the reference type object (or nullable value type) you are trying to access evaluates to null. So instead of having to do something like this:

            int? myNullableInt = null;
            int myInt;

            if (myNullableInt == null)
            {
                myInt = -1;
            }
            else
            {
                myInt = (int)myNullableInt;
            }

You can do this in-line:

myInt = myNullableInt ?? -1;

Apologies for the heavily contrived and quite pointless example, but at least it gets the syntax down and should make it apparent how useful this operator can be when dealing with a mixture of nullable and non-nullable types.

Tags: , , , , , , ,

No Comments


Making a function call on another thread using the C# Dispatcher class

There may be a situation when you need to execute a function on a different thread, such as ensuring that calls across the interface between a multi-threaded dll and its single-threaded user are made on the same, single thread. To achive this, you can use the target thread’s Dispatcher object as follows:

  1. Create a delegate of the function you wish to be able to call:
    public delegate void MyDelegate(int i, string str);
    public class TargetThreadClass
    {
        public TargetThreadClass()
        {
            MyDelegate del = new MyDelegate(this.FuncToExec);
        }
        public void FuncToExec(int i, string str)
        {
           // Do something
       }
    }
  2. Within the target thread, create an instance of a Dispatcher object and set it to the thread’s current dispatcher:
    Dispatcher UserDispatcher = Dispatcher.CurrentDispatcher;

    Then pass this dispatcher, along with the delegate into the source thread.

  3. Then to call FuncToExec on the target thread, use:
    UserDispatcher.Invoke(del, new object[] { 123, "arg string"});

    Where the first parameter of Invoke is the delegate itself and the second an array of the delegate’s parameters (if any), in this example the delegate takes an int and a string.

Tags: , , , ,

2 Comments


Non-blocking keyboard input in C#

I know this one is pretty noddy, but these posts are as much a way of me storing code snippets I might need quickly in the future as any form of ‘public service’ so I’ll post it anyway.

I quite frequently want to capture key presses in my apps, and to do this I use Console.ReadKey which returns a nice ConsoleKeyInfo object to tell me what’s just been pressed. The problem is this call blocks until a key has been pressed and sometimes I don’t want to block out the main execution thread or have to create a separate thread *just* to handle the keyboard input.

This is where Console’s KeyAvailable property comes in.  It returns true if there is a key press available in the input stream without blocking allowing you to do something like:

while (true)
{
    if (Console.KeyAvailable)
    {
        ConsoleKeyInfo key = Console.ReadKey(true);
        switch (key.Key)
        {
            case ConsoleKey.F1:
                Console.WriteLine("You pressed F1!");
                break;
            default:
                break;
        }
    }
    // Do something more useful
}

Tags: , , , , , ,

No Comments


Returning errorlevels from C# applications

Something came up today which turned out to be a bit of a blast from the past. If you want to check the return value of a C# console application (for use in an old school batch file for example) you can’t rely on the return value of main (as you would in C for example), but have to set the value of System.Environment.ExitCode instead. The advantage to this over a single return statement is this call sets the exit code and won’t actually exit your program at that point, see below.

static void Main(string[] args)
{
	// program code...
	// now set the return value to 1
	System.Environment.ExitCode = 1
}

This example returns 1, which can then be picked up by some good ol’ fashioned batch command-goodness. I’m already reminiscing back to my 1000+ line BBS mailer batch file back in 1995!

Also came across this which provides guidance on the special meanings of some exit codes.

Tags: , , ,

1 Comment



SetPageWidth