<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Richard Dutton &#187; C#</title>
	<atom:link href="http://www.dutton.me.uk/category/software-development/csharp/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dutton.me.uk</link>
	<description>Software Engineering, Photography, Travel, Stuff...</description>
	<lastBuildDate>Wed, 07 Sep 2011 16:12:23 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>RichTextBox ScrollToCaret() bug</title>
		<link>http://www.dutton.me.uk/2011/08/31/richtextbox-scrolltocaret-bug/</link>
		<comments>http://www.dutton.me.uk/2011/08/31/richtextbox-scrolltocaret-bug/#comments</comments>
		<pubDate>Wed, 31 Aug 2011 09:23:02 +0000</pubDate>
		<dc:creator>richard</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Windows Forms]]></category>
		<category><![CDATA[bug]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[richtextbox]]></category>
		<category><![CDATA[scroll]]></category>
		<category><![CDATA[scrolltocaret]]></category>
		<category><![CDATA[win forms]]></category>
		<category><![CDATA[windows forms]]></category>
		<category><![CDATA[winforms]]></category>

		<guid isPermaLink="false">http://www.dutton.me.uk/?p=395</guid>
		<description><![CDATA[I recently needed to add selective colour to text in a Windows Forms TextBox. TextBox doesn&#8217;t support this, but its close sibling RichTextBox does and as they both derive from TextBoxBase, the conversion in code was painless. The original TextBox control would automatically set the caret (cursor) position to the end of the text and [...]]]></description>
			<content:encoded><![CDATA[<p>I recently needed to add selective colour to text in a Windows Forms TextBox. TextBox doesn&#8217;t support this, but its close sibling RichTextBox does and as they both derive from TextBoxBase, the conversion in code was painless.</p>
<p>The original TextBox control would automatically set the caret (cursor) position to the end of the text and use ScrollToCaret() to ensure the last line was always visible after dynamically adding content. This doesn&#8217;t quite work the same when called on a RichTextBox as it appears to scroll until just the very top of the caret is visible, resulting in at best a few pixels of the last line&#8217;s text visible.</p>
<p>Quite a bit of googling of the problem reveals lots of discussion but not much in the way of a suggested solution.</p>
<p>Fortunately, user32.dll provides calls we can use to set the scroll position and we can access these unmanaged functions through P/Invoke as follows:</p>
<pre class="c-sharp">
[StructLayout(LayoutKind.Sequential)]
public class POINT
{
    public int x;
    public int y;

    public POINT()
    {
    }

    public POINT(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}

const int SB_VERT = 1;
const int EM_SETSCROLLPOS = 0x0400 + 222;

[DllImport("user32", CharSet = CharSet.Auto)]
static extern bool GetScrollRange(IntPtr hWnd, int nBar, out int lpMinPos, out int lpMaxPos);

[DllImport("user32", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, POINT lParam)
</pre>
<p>Then, when you want to set the scroll position (&#8220;control&#8221; is your RichTextBox instance):</p>
<pre class="c-sharp">
int min, max;
GetScrollRange(control.Handle, SB_VERT, out min, out max);
SendMessage(control.Handle, EM_SETSCROLLPOS, 0, new POINT(0, max - control.Height));
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.dutton.me.uk/2011/08/31/richtextbox-scrolltocaret-bug/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Microsoft 70-511 Exam Passed</title>
		<link>http://www.dutton.me.uk/2011/08/15/microsoft-70-511-exam-passed/</link>
		<comments>http://www.dutton.me.uk/2011/08/15/microsoft-70-511-exam-passed/#comments</comments>
		<pubDate>Mon, 15 Aug 2011 15:06:15 +0000</pubDate>
		<dc:creator>richard</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[.net framework 4]]></category>
		<category><![CDATA[70-511]]></category>
		<category><![CDATA[certified]]></category>
		<category><![CDATA[exam]]></category>
		<category><![CDATA[mcts]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[microsoft certified technology specialist]]></category>
		<category><![CDATA[windows applications]]></category>

		<guid isPermaLink="false">http://www.dutton.me.uk/?p=391</guid>
		<description><![CDATA[Last week I passed the Microsoft 70-511: Windows Application Development with Microsoft .NET Framework 4 exam, making me a Microsoft Certified Technology Specialist! This is the first of four exams I&#8217;m aiming to complete in order to become a Microsoft Certified Professional Developer.]]></description>
			<content:encoded><![CDATA[<p>Last week I passed the Microsoft 70-511: Windows Application Development with Microsoft .NET Framework 4 exam, making me a Microsoft Certified Technology Specialist!</p>
<p><a href="http://www.dutton.me.uk/wp-content/uploads/2011/08/MCTSrgb_1369.png"><img class="aligncenter size-full wp-image-392" title="MCTS 70-511" src="http://www.dutton.me.uk/wp-content/uploads/2011/08/MCTSrgb_1369.png" alt="" width="366" height="80" /></a></p>
<p>This is the first of four exams I&#8217;m aiming to complete in order to become a Microsoft Certified Professional Developer.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dutton.me.uk/2011/08/15/microsoft-70-511-exam-passed/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How to handle Command Line Arguments in WPF Applications</title>
		<link>http://www.dutton.me.uk/2011/02/21/how-to-handle-command-line-arguments-in-wpf-applications/</link>
		<comments>http://www.dutton.me.uk/2011/02/21/how-to-handle-command-line-arguments-in-wpf-applications/#comments</comments>
		<pubDate>Mon, 21 Feb 2011 16:12:03 +0000</pubDate>
		<dc:creator>richard</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Application]]></category>
		<category><![CDATA[arguments]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[command line]]></category>
		<category><![CDATA[command line arguments]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Startup]]></category>
		<category><![CDATA[StartupEventArgs]]></category>

		<guid isPermaLink="false">http://www.dutton.me.uk/?p=378</guid>
		<description><![CDATA[I&#8217;ve not considered it before as up to now I haven&#8217;t required it, but obviously in a WPF Application you don&#8217;t have a nice static void Main(string[] args) { ... } with a useful string array of arguments like you do in a regular C# console app, so how do you access them? In a [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve not considered it before as up to now I haven&#8217;t required it, but obviously in a WPF Application you don&#8217;t have a nice</p>
<pre name="code" class="c-sharp">static void Main(string[] args)
{
...
}</pre>
<p>with a useful string array of arguments like you do in a regular C# console app, so how do you access them?</p>
<p>In a default WPF application, the entry point to the program is <span id="more-378"></span>the <strong>Application</strong> object. This object has an event <strong>Startup</strong> which is fired, unsurprisingly on startup of your app and contains <strong>StartupEventArgs</strong>. You can query this object to get to your arguments as follows:</p>
<pre name="code" class="c-sharp">
public partial class App : Application
 {
   ///
   /// A static string array containing our start-up command line arguments
   ///
   public static string[] Args;

   protected override void OnStartup(StartupEventArgs e)
   {
       Args = e.Args;
       base.OnStartup(e);
   }
}</pre>
<p>Store them in a static member and then you can access them elsewhere in your application as <strong>Apps.Args</strong>.</p>
<p>So far, so good. But what happens if you actually need some arguments to run, and so want to check and fail gracefully if they don&#8217;t exist? I found that if I checked in my <strong>OnStartup</strong> handler, I still couldn&#8217;t halt the start-up of my application on error.</p>
<p>Instead, I added a <strong>Loaded</strong> event handler to my MainWindow. This is fired once the Application and MainWindow have been loaded so I know I my static Args member will have been set by the time it is fired. I can do all the validation I want on my argument array and decide whether to continue execution or stop and provide an error to the user.</p>
<pre name="code" class="c-sharp">
public MainWindow()
{
     InitializeComponent();

     // Make sure the command line arguments have been processed
     this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
}

void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    if (App.Args.Length == 1)
    {
        // everything is good, do stuff
    }
    else
    {
        // ERROR!!!
        MessageBox.Show("Not enough arguments!");
        App.Current.Shutdown();
     }
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.dutton.me.uk/2011/02/21/how-to-handle-command-line-arguments-in-wpf-applications/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>OK &#8211; Cancel behaviour with data binding in WPF</title>
		<link>http://www.dutton.me.uk/2010/10/11/ok-cancel-behaviour-with-data-binding-in-wpf/</link>
		<comments>http://www.dutton.me.uk/2010/10/11/ok-cancel-behaviour-with-data-binding-in-wpf/#comments</comments>
		<pubDate>Mon, 11 Oct 2010 14:05:33 +0000</pubDate>
		<dc:creator>richard</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[GetBindingExpression]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.dutton.me.uk/?p=346</guid>
		<description><![CDATA[As much as I am a fan of the Mac OSX and iPhone approach of modifying a setting and having it apply immediately without any further user interaction, my current work involves designing GUIs for Industrial Control and Automation systems where the old &#60;OK&#62; &#60;Cancel&#62; buttons are still required (often by law) which brought up [...]]]></description>
			<content:encoded><![CDATA[<p>As much as I am a fan of the Mac OSX and iPhone approach of modifying a setting and having it apply immediately without any further user interaction, my current work involves designing GUIs for Industrial Control and Automation systems where the old &lt;OK&gt; &lt;Cancel&gt; buttons are still required (often by law) which brought up the question of how to do this in WPF with data binding where, depending on the control, updates are triggered either in real-time or on loss of focus.</p>
<p>The answer is in one of the attributes of Binding called &#8220;<strong>UpdateSourceTrigger</strong>&#8221; which has the following options:</p>
<ul>
<li><strong>LostFocus</strong> &#8211; Update bound property when the control loses focus (TextBox default).</li>
<li><strong>PropertyChanged</strong> &#8211; Update bound property in real-time.</li>
<li><strong>Explicit </strong>- Update bound property when UpdateSource() is called</li>
</ul>
<p>It is this last setting which allows us to delay updating our bound property until we tell it to.</p>
<p>Let&#8217;s say we have a UserControl containing a TextBox, &#8216;MyTextBox&#8217; which is bound to some Dependency Property and two buttons, &#8216;OK&#8217; and &#8216;Cancel&#8217;. Depending on how you hook your buttons up (with RoutedCommands or click handlers (eugh!)) the &#8216;OK&#8217; button&#8217;s code looks like this:</p>
<pre name="code" class="c-sharp">
BindingExpression be = MyTextBox.GetBindingExpression(TextBox.TextProperty);
if (be!=null) be.UpdateSource();</pre>
<p>The &#8216;Cancel&#8217; button&#8217;s code does the reverse:</p>
<pre name="code" class="c-sharp">
BindingExpression be = MyTextBox.GetBindingExpression(TextBox.TextProperty);
if (be!=null) be.UpdateTarget();</pre>
<p>Et voila! Your dependency property will now only update when you want it to.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dutton.me.uk/2010/10/11/ok-cancel-behaviour-with-data-binding-in-wpf/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Handling events from within a ControlTemplate in WPF</title>
		<link>http://www.dutton.me.uk/2010/02/13/handling-events-from-within-a-controltemplate-in-wpf/</link>
		<comments>http://www.dutton.me.uk/2010/02/13/handling-events-from-within-a-controltemplate-in-wpf/#comments</comments>
		<pubDate>Sat, 13 Feb 2010 07:00:42 +0000</pubDate>
		<dc:creator>richard</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[button]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[event]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[events inside a ControlTemplate]]></category>
		<category><![CDATA[events within a ControlTemplate]]></category>
		<category><![CDATA[GetTemplateChild]]></category>
		<category><![CDATA[OnApplyTemplate]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[RoutedEvent]]></category>
		<category><![CDATA[RoutedEventhandler]]></category>

		<guid isPermaLink="false">http://www.dutton.me.uk/?p=323</guid>
		<description><![CDATA[Here&#8217;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&#8217;ve got an object, TextEntryBox, which dervies from a TextBox (it provides some custom event handlers when text is entered, but to all [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s an interesting one that had me stumped for a few hours.</p>
<p>Following on from my <a href="http://www.dutton.me.uk/2010/02/13/how-to-create-a-controltemplate-for-a-wpf-textbox/" target="_blank">previous post</a>, where I explained how to create a ControlTemplate to style a TextBox in WPF, I&#8217;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&#8217;s a regular TextBox).</p>
<p>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&#8217;s another blog post!). I came up with this:<br />
<span id="more-323"></span></p>
<pre name="code" class="xml">
<Style TargetType="{x:Type my:EntryTextBox}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type my:EntryTextBox}">
                <DockPanel>
                    <Border BorderThickness="1"
                    	HorizontalAlignment="Stretch"
                    	BorderBrush="DarkGray"
                    	Background="White"
                    	Width="100">
                        <DockPanel>
                            <Button x:Name="PART_KeyboardPopupButton"
                            	DockPanel.Dock="Right"
                            	Width="15"
                            	Height="10"/>
                            <ScrollViewer Margin="0"
                            	Background="Transparent"
                            	HorizontalAlignment="Stretch"
                            	x:Name="PART_ContentHost"/>
                        </DockPanel>
                    </Border>
                </DockPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</pre>
<p>All&#8217;s well and good, until I want to try and handle the Click event for that button within my TextEntryBox class. Even Matthew MacDonald&#8217;s &#8220;Pro WPF in C# 2008&#8243; which has proved a lifesaver for all things WPF since I&#8217;ve been working with this technology only had the following words of wisdom;</p>
<blockquote><p>&#8220;You can&#8217;t attach event handlers in the control template. Instead, you&#8217;ll need to give your elements recognizable names and attach event handlers to them programmatically in the control constructor&#8221;</p></blockquote>
<p>But whatever I tried I couldn&#8217;t access the event in my constructor, until I remembered the seperation between the visual and logical trees in WPF.</p>
<p>The template is applied at runtime, and so elements contained within it it are part of the visual tree. My class, and therefore my class&#8217; constructor is executed within the logical tree, so I needed to attach my event handler after the template had been applied. You can do this by overriding OnApplyTemplate in your class, obtain the template that&#8217;s being applied, and then you have access to the named button&#8217;s events, like this:</p>
<pre name="code" class="c-sharp">
public override void OnApplyTemplate()
{
    DependencyObject d = GetTemplateChild("PART_KeyboardPopupButton");
    if (d != null)
    {
        (d as Button).Click += new RoutedEventHandler(KeyboardPopupButton_Click);
    }

    base.OnApplyTemplate();
}
</pre>
<p>Note the null check, as someone could have applied a completely different template to the object.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dutton.me.uk/2010/02/13/handling-events-from-within-a-controltemplate-in-wpf/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>How to create a ControlTemplate for a WPF TextBox</title>
		<link>http://www.dutton.me.uk/2010/02/13/how-to-create-a-controltemplate-for-a-wpf-textbox/</link>
		<comments>http://www.dutton.me.uk/2010/02/13/how-to-create-a-controltemplate-for-a-wpf-textbox/#comments</comments>
		<pubDate>Sat, 13 Feb 2010 06:00:10 +0000</pubDate>
		<dc:creator>richard</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[ContentHost]]></category>
		<category><![CDATA[ControlTemplate]]></category>
		<category><![CDATA[PART_ContentHost]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[ScrollViewer]]></category>
		<category><![CDATA[style]]></category>
		<category><![CDATA[TextBox]]></category>
		<category><![CDATA[x:Name]]></category>
		<category><![CDATA[x:Name="Part_ContentHost"]]></category>

		<guid isPermaLink="false">http://www.dutton.me.uk/?p=325</guid>
		<description><![CDATA[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&#8217;s used in WPF? A: The answer was hidden in the depths of the [...]]]></description>
			<content:encoded><![CDATA[<p>This is a short post, but has one specific piece of information I want to keep.</p>
<p>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&#8217;s used in WPF?</p>
<p>A: The answer was hidden in the depths of the MSDN Documentation. You have to include a &lt;ScrollViewer&gt; within your ControlTemplate with an x:Name value of &#8220;PART_ContentHost&#8221;.</p>
<p>Here&#8217;s a noddy example:</p>
<pre name="code" class="xml">
<Style TargetType="{x:Type TextBox}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TextBox}">
                <DockPanel>
                    <Border BorderThickness="1"
                               BorderBrush="DarkGray"
                               Background="White"
                               Width="100">
                        <DockPanel>
                            <ScrollViewer Background="Transparent"
                                               HorizontalAlignment="Stretch"
                                               x:Name="PART_ContentHost"/>
                        </DockPanel>
                    </Border>
                </DockPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.dutton.me.uk/2010/02/13/how-to-create-a-controltemplate-for-a-wpf-textbox/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>C#&#8217;s Null-Coalescing (??) Operator</title>
		<link>http://www.dutton.me.uk/2009/04/22/cs-null-coalescing-operator/</link>
		<comments>http://www.dutton.me.uk/2009/04/22/cs-null-coalescing-operator/#comments</comments>
		<pubDate>Wed, 22 Apr 2009 07:31:10 +0000</pubDate>
		<dc:creator>richard</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[c# operator]]></category>
		<category><![CDATA[null]]></category>
		<category><![CDATA[null coalescing]]></category>
		<category><![CDATA[null coalescing operator]]></category>
		<category><![CDATA[nullable]]></category>
		<category><![CDATA[nullable type]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.dutton.me.uk/?p=212</guid>
		<description><![CDATA[Although I&#8217;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 [...]]]></description>
			<content:encoded><![CDATA[<p>Although I&#8217;ve always been a big fan of the <a href="http://msdn.microsoft.com/en-us/library/ty67wk28(VS.80).aspx" target="_blank">ternary operator</a>, 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 <a href="http://msdn.microsoft.com/en-us/library/ms173224(VS.80).aspx" target="_blank">?? operator</a>.</p>
<p>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:</p>
<pre name="code" class="csharp">
            int? myNullableInt = null;
            int myInt;

            if (myNullableInt == null)
            {
                myInt = -1;
            }
            else
            {
                myInt = (int)myNullableInt;
            }
</pre>
<p>You can do this in-line:</p>
<pre name="code" class="csharp">
myInt = myNullableInt ?? -1;
</pre>
<p>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.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dutton.me.uk/2009/04/22/cs-null-coalescing-operator/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making a function call on another thread using the C# Dispatcher class</title>
		<link>http://www.dutton.me.uk/2009/03/30/making-a-function-call-on-another-thread-with-the-c-dispatcher-class/</link>
		<comments>http://www.dutton.me.uk/2009/03/30/making-a-function-call-on-another-thread-with-the-c-dispatcher-class/#comments</comments>
		<pubDate>Mon, 30 Mar 2009 18:00:09 +0000</pubDate>
		<dc:creator>richard</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[Dispatcher]]></category>
		<category><![CDATA[multi-threaded]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[threads]]></category>

		<guid isPermaLink="false">http://www.dutton.me.uk/?p=181</guid>
		<description><![CDATA[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&#8217;s Dispatcher object as follows: Create a delegate [...]]]></description>
			<content:encoded><![CDATA[<p>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&#8217;s Dispatcher object as follows:</p>
<ol>
<li>Create a delegate of the function you wish to be able to call:
<pre name="code" class="c-sharp">
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
   }
}</pre>
</li>
<li>Within the target thread, create an instance of a Dispatcher object and set it to the thread&#8217;s current dispatcher:
<pre name="code" class="c-sharp">
Dispatcher UserDispatcher = Dispatcher.CurrentDispatcher;</pre>
<p>Then pass this dispatcher, along with the delegate into the source thread.</li>
<li>Then to call FuncToExec on the target thread, use:
<pre name="code" class="c-sharp">
UserDispatcher.Invoke(del, new object[] { 123, "arg string"});</pre>
<p>Where the first parameter of Invoke is the delegate itself and the second an array of the delegate&#8217;s parameters (if any), in this example the delegate takes an int and a string.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.dutton.me.uk/2009/03/30/making-a-function-call-on-another-thread-with-the-c-dispatcher-class/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Non-blocking keyboard input in C#</title>
		<link>http://www.dutton.me.uk/2009/02/24/non-blocking-keyboard-input-in-c/</link>
		<comments>http://www.dutton.me.uk/2009/02/24/non-blocking-keyboard-input-in-c/#comments</comments>
		<pubDate>Tue, 24 Feb 2009 17:30:39 +0000</pubDate>
		<dc:creator>richard</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[console keyboard input]]></category>
		<category><![CDATA[Console.KeyAvailable]]></category>
		<category><![CDATA[Console.ReadKey]]></category>
		<category><![CDATA[non-blocking]]></category>
		<category><![CDATA[non-blocking keyboard input]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.dutton.me.uk/?p=109</guid>
		<description><![CDATA[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 &#8216;public service&#8217; so I&#8217;ll post it anyway. I quite frequently want to capture key presses in my apps, and to do this I use [...]]]></description>
			<content:encoded><![CDATA[<p>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 &#8216;public service&#8217; so I&#8217;ll post it anyway.</p>
<p>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&#8217;s just been pressed. The problem is this call blocks until a key has been pressed and sometimes I don&#8217;t want to block out the main execution thread or have to create a separate thread *just* to handle the keyboard input.</p>
<p>This is where Console&#8217;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:</p>
<pre name="code" class="c-sharp">
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
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.dutton.me.uk/2009/02/24/non-blocking-keyboard-input-in-c/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Returning errorlevels from C# applications</title>
		<link>http://www.dutton.me.uk/2009/01/22/returning-errorlevels-from-c-applications/</link>
		<comments>http://www.dutton.me.uk/2009/01/22/returning-errorlevels-from-c-applications/#comments</comments>
		<pubDate>Thu, 22 Jan 2009 16:19:58 +0000</pubDate>
		<dc:creator>richard</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[batch file]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[errorlevel]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.dutton.me.uk/?p=20</guid>
		<description><![CDATA[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&#8217;t rely on the return value of main (as you would in C for [...]]]></description>
			<content:encoded><![CDATA[<p>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&#8217;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&#8217;t actually exit your program at that point, see below.</p>
<pre name="code" class="c-sharp">
static void Main(string[] args)
{
	// program code...
	// now set the return value to 1
	System.Environment.ExitCode = 1
}
</pre>
<p>This example returns 1, which can then be picked up by some good ol&#8217; fashioned batch command-goodness. I&#8217;m already reminiscing back to my 1000+ line BBS mailer batch file back in 1995!</p>
<p>Also came across <a href="http://tldp.org/LDP/abs/html/exitcodes.html" target="_blank">this</a> which provides guidance on the special meanings of some exit codes.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dutton.me.uk/2009/01/22/returning-errorlevels-from-c-applications/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

