<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blogs.msdn.com/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>David Rickard's Tech Blog</title><link>http://blogs.msdn.com/b/davidrickard/</link><description>Thoughts on C#, WPF and programming in general</description><dc:language>en-US</dc:language><generator>Telligent Evolution Platform Developer Build (Build: 5.6.50428.7875)</generator><item><title>DateTime and DateTimeOffset in .NET: Good practices and common pitfalls</title><link>http://blogs.msdn.com/b/davidrickard/archive/2012/04/07/system-datetime-good-practices-and-common-pitfalls.aspx</link><pubDate>Sat, 07 Apr 2012 00:37:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10291584</guid><dc:creator>RandomEngy</dc:creator><slash:comments>7</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/davidrickard/rsscomments.aspx?WeblogPostID=10291584</wfw:commentRss><comments>http://blogs.msdn.com/b/davidrickard/archive/2012/04/07/system-datetime-good-practices-and-common-pitfalls.aspx#comments</comments><description>&lt;p&gt;It becomes necessary to deal with dates and times in most .NET programs. A lot of programs use DateTime but that structure is frought with potential issues when you start serializing, parsing, comparing&amp;nbsp;and displaying dates from&amp;nbsp;different time zones and cultures. In this post I will go over these issues and&amp;nbsp;the APIs and practices you should use to avoid them.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Background&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The DateTime structure stores only two pieces of information: Ticks and Kind. 1 tick is 100 nanoseconds (10,000 ticks in a millisecond). The ticks counter represents how many 100ns ticks you are away from 1/1/0001 12:00 AM. It's the part that determines that it's April 6th, 2012, 3:32:07 PM.&lt;/p&gt;
&lt;p&gt;Another bit of data is the Kind: represented as a DateTimeKind enumeration. Utc, Local and Unspecified&amp;nbsp;are the possible values. Utc means that the ticks counter represents a &lt;a title="Coordinated Universal Time" href="http://en.wikipedia.org/wiki/Coordinated_Universal_Time"&gt;Coordinated Universal Time&lt;/a&gt; (that doesn't change due to daylight savings&amp;nbsp;or time zones). Local means that it represents the local time of whatever time zone the computer is set to. This one is sensitive to daylight savings. Note that a timezone offset is &lt;em&gt;not&lt;/em&gt; built in to the DateTime structure. It can only get back to a real UTC time by checking the current time zone settings on the computer. ToUniversalTime() and ToLocalTime() will do these conversions. It will return a new DateTime value with the Ticks adjusted to get the correct year/month/day and with the requested type. Calling ToUniversalTime() on a UTC DateTime or ToLocalTime() on a Local DateTime has no effect. Remember that these functions are generating a &lt;em&gt;new&lt;/em&gt; DateTime value and not modifying the original.&lt;/p&gt;
&lt;p&gt;There's also&amp;nbsp;a third type: Unspecified. This means we don't know whether it's local or UTC. All we know is the year, month, day, etc. When working with DateTime values, Unspecified is not very helpful since we don't know what to do when we want to get a local or UTC time from it. If you call ToUniversalTime() on one of these, it assumes that the type must have been Local and converts based on that. If you call ToLocalTime() it assumes that the type must have been UTC and converts in that direction.&lt;/p&gt;
&lt;p&gt;DateTimeOffset is a newer structure. It is also based on ticks but instead of storing a Kind, it keeps track of the offset from UTC as a TimeSpan. A DateTimeOffset always knows what time zone it's in. Calling ToUniversalTime() will always result in a TimeSpan.Zero offset, and ToLocalTime() will convert and result in an offset of the user's current time zone.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Use DateTimeOffset, not DateTime&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;DateTime has countless traps in it that are designed to give your code bugs:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;DateTime values with DateTimeKind.Unspecified are bad news. It's common for code&amp;nbsp;to call ToUniversalTime() or ToLocalTime() to make sure it's got&amp;nbsp;the&amp;nbsp;date properly ready for storage or display respectively.&amp;nbsp;If you call ToUniversalTime() it converts X hours in one direction, but if you call ToLocalTime() on it, it converts X hours in the opposite direction. Both of those can't possibly be correct&lt;strong&gt;.&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;DateTime doesn't care about UTC/Local when doing comparisons. &lt;span class="selflink"&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;It only cares about the number of Ticks on the objects. It could not care less that you've lovingly specified that value A is most certainly UTC and value B is local; it won't do any conversions for you. 7:30 AM Local is always going to be evaluated as less than 8:22 AM UTC, even if your timezone is EDT and really the first time was 11:30 AM UTC.&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;DateTime values are not aware of standard format strings. For instance the &lt;span class="selflink"&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;"r" (RFC1123, the format used in HTTP headers) and "u" (universal sortable) formats both put UTC markers in the string you serialize to. If you call .ToString("u") on a local time, DateTime will happily label your local time as UTC without doing any conversion. The basically guarantees disaster when it gets parsed back in again.&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;Parsing a string that has a UTC marker with DateTime does not guarantee a UTC time. &lt;span class="selflink"&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;If you run DateTime.Parse("2012-04-06 23:46:23Z") you might expect the result to be a UTC DateTime since the "Z" UTC flag is right there in the string, but you do not. It will correctly note that it is dealing with a UTC time, then promptly convert it to a Local time. It's still technically correct, but it can result in the hours count changing when you are not expecting it to.&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;But DateTimeOffset doesn't have any of these problems! It's the newer, more robust version; think of it as DateTime v2. They couldn't fix the old DateTime object because that might break existing code that was relying on the bad behavior.&lt;/p&gt;
&lt;p&gt;So you'll want to use DateTimeOffset in any situation that you're referring to a specific point in time. You might still use DateTime for things like general dates (July 4th, 1776) or store hours (9AM-5PM), since they are not affected by time zones.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Pick the right format when serializing&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;/strong&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;It's common to convert DateTimeOffset values to strings for storage or sending them somewhere else. &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;The &lt;a title="list of standard date and time format strings" href="http://msdn.microsoft.com/en-us/library/az4se3k1.aspx"&gt;list of standard date and time format strings&lt;/a&gt; is helpful when you are contemplating how to do this.&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt; These are used with the DateTimeOffset.ToString method: for example myDate.ToString("u"). Note how with most of the standard formats you get different&amp;nbsp;values for different cultures: different month names, swapped month/day places, etc. If you use one of these to serialize and Parse back in, it might work if you have the same culture on both sides, but will break if one side uses a different culture. You can get failed parses or swapped month/day values. Only the "o", "r", "s" and "u" formats are culture-invariant. Use one of those for serialization:&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;table border="0"&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Format string&lt;/td&gt;
&lt;td&gt;Name&lt;/td&gt;
&lt;td&gt;Example&lt;/td&gt;
&lt;td&gt;&amp;nbsp;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;"o"&lt;/td&gt;
&lt;td&gt;Round-trip&lt;/td&gt;
&lt;td&gt;2012-04-17T16:46:48.0820143+00:00 &lt;em&gt;(UTC)&lt;/em&gt;&lt;br /&gt;2012-04-17T09:46:48.0820143-07:00 &lt;em&gt;(local)&lt;/em&gt;&lt;/td&gt;
&lt;td&gt;The only format that preserves the DateTimeOffset fully. The others round to the nearest second.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;"r"&lt;/td&gt;
&lt;td&gt;RFC1123&lt;/td&gt;
&lt;td&gt;Tue, 17 Apr 2012 16:46:48 GMT&lt;/td&gt;
&lt;td&gt;Used for HTTP headers&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;"u"&lt;/td&gt;
&lt;td&gt;Universal sortable&lt;/td&gt;
&lt;td&gt;2012-04-17 16:46:48Z&lt;/td&gt;
&lt;td&gt;&amp;nbsp;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;"s"&lt;/td&gt;
&lt;td&gt;Sortable&lt;/td&gt;
&lt;td&gt;2012-04-17T16:46:48 &lt;em&gt;(UTC)&lt;/em&gt;&lt;br /&gt;2012-04-17T09:46:48 &lt;em&gt;(local)&lt;/em&gt;&lt;/td&gt;
&lt;td&gt;Not a great format for this use as it has no timezone or UTC marker and can change based on what offset you have&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;Conclusion&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;Use DateTimeOffset and be careful with serialization. If you're dealing with legacy code that's using DateTime, be aware of all the timezone-related pitfalls when comparing, serializing, parsing and converting.&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;One final issue...&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;&lt;span class="selflink"&gt;If it is Coordinated Universal Time, why is the acronym UTC and not CUT? When the English and the French were getting together to work out the notation, the french wanted TUC, for Temps Universel Coordonn&amp;eacute;. UTC was a compromise: it fit equally badly for each language. :)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10291584" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/davidrickard/archive/tags/datetime/">datetime</category><category domain="http://blogs.msdn.com/b/davidrickard/archive/tags/utc/">utc</category><category domain="http://blogs.msdn.com/b/davidrickard/archive/tags/-net/">.net</category><category domain="http://blogs.msdn.com/b/davidrickard/archive/tags/datetimeoffset/">datetimeoffset</category></item><item><title>Using the Dispatcher with MVVM</title><link>http://blogs.msdn.com/b/davidrickard/archive/2010/04/01/using-the-dispatcher-with-mvvm.aspx</link><pubDate>Thu, 01 Apr 2010 03:27:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9988555</guid><dc:creator>RandomEngy</dc:creator><slash:comments>7</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/davidrickard/rsscomments.aspx?WeblogPostID=9988555</wfw:commentRss><comments>http://blogs.msdn.com/b/davidrickard/archive/2010/04/01/using-the-dispatcher-with-mvvm.aspx#comments</comments><description>&lt;p&gt;When writing an MVVM application, you want to separate from the UI. However you also need to make sure that UI updates happen on the UI thread. Changes made through INotifyPropertyChanged get automatically marshaled to the UI thread, so in most cases you&amp;rsquo;ll be fine. However, when using INotifyCollectionChanged (such as with an ObservableCollection), these changes are &lt;em&gt;not&lt;/em&gt; marshaled to the UI thread.&lt;/p&gt;
&lt;p&gt;This means that unless you modify your collection on the UI thread, you&amp;rsquo;ll get a cross threading error. Thus the problem. We&amp;rsquo;re in the ViewModel and we don&amp;rsquo;t have access to the Dispatcher. That&amp;rsquo;s on a View object. How do we update the collection on the UI thread?&lt;/p&gt;
&lt;p&gt;I came up with a small static class to help with this:&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;&lt;/span&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;span style="color: blue;"&gt;public&lt;/span&gt; &lt;span style="color: blue;"&gt;static&lt;/span&gt; &lt;span style="color: blue;"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af;"&gt;DispatchService&lt;/span&gt;
{
    &lt;span style="color: blue;"&gt;public&lt;/span&gt; &lt;span style="color: blue;"&gt;static&lt;/span&gt; &lt;span style="color: blue;"&gt;void&lt;/span&gt; Invoke(&lt;span style="color: #2b91af;"&gt;Action&lt;/span&gt; action)
    {
        &lt;span style="color: #2b91af;"&gt;Dispatcher&lt;/span&gt; dispatchObject = &lt;span style="color: #2b91af;"&gt;Application&lt;/span&gt;.Current.Dispatcher;
        &lt;span style="color: blue;"&gt;if&lt;/span&gt; (dispatchObject == &lt;span style="color: blue;"&gt;null&lt;/span&gt; || dispatchObject.CheckAccess())
	{
            action();
        }
        &lt;span style="color: blue;"&gt;else&lt;/span&gt;
        {
            dispatchObject.Invoke(action);
        }
    }
}&lt;/pre&gt;
&lt;p&gt;When your ViewModel gives the DispatchService actions, it can run them on the correct thread. Which is, in the case of unit tests, always the current thread. A call to the DispatchService may look like this:&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: #2b91af;"&gt;DispatchService&lt;/span&gt;.Invoke(() =&amp;gt;
{
    &lt;span style="color: blue;"&gt;this&lt;/span&gt;.MyCollection.Add(&lt;span style="color: #a31515;"&gt;"new value"&lt;/span&gt;);
});&lt;/pre&gt;
&lt;p&gt;The use of a simple lambda statement makes it a relatively lightweight way of updating on the correct thread.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9988555" width="1" height="1"&gt;</description></item><item><title>Saving window size and location in WPF and WinForms</title><link>http://blogs.msdn.com/b/davidrickard/archive/2010/03/09/saving-window-size-and-location-in-wpf-and-winforms.aspx</link><pubDate>Tue, 09 Mar 2010 03:18:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9975248</guid><dc:creator>RandomEngy</dc:creator><slash:comments>10</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/davidrickard/rsscomments.aspx?WeblogPostID=9975248</wfw:commentRss><comments>http://blogs.msdn.com/b/davidrickard/archive/2010/03/09/saving-window-size-and-location-in-wpf-and-winforms.aspx#comments</comments><description>&lt;p&gt;A common user interface tweak is to save the size and location of a window and restore that state when the program starts up again. That way, the users don&amp;rsquo;t need to re-do their work of resizing and moving the windows to where they want them. However I&amp;rsquo;ve found that there isn&amp;rsquo;t really a convenient way to do with in C#. Many solutions focus on recording the window width, height, x and y coordinates and current state (maximized, restored, etc), then applying all those values again on startup. But then you have to deal with edge cases: What if the user has changed resolutions since your program last ran? What if it was present on a monitor that&amp;rsquo;s now disconnected?&lt;/p&gt;
&lt;p&gt;Fortunately, there are a couple of native Windows functions that can do all this work for us: &lt;a href="http://msdn.microsoft.com/en-us/library/ms633544%28VS.85%29.aspx"&gt;SetWindowPlacement&lt;/a&gt; and &lt;a href="http://msdn.microsoft.com/en-us/library/ms633518%28VS.85%29.aspx"&gt;GetWindowPlacement&lt;/a&gt;. MSDN has a &lt;a href="http://msdn.microsoft.com/en-us/library/aa972163.aspx"&gt;sample&lt;/a&gt; demonstrating how to PInvoke to these functions in a WPF project, but it&amp;rsquo;s got a few issues with it. For one, it&amp;rsquo;s trying to store the placement as a custom type in settings, which can cause strange errors every time you open your Settings file. Here&amp;rsquo;s my take on it:&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;using &lt;/span&gt;System;
&lt;span style="color: blue;"&gt;using &lt;/span&gt;System.IO;
&lt;span style="color: blue;"&gt;using &lt;/span&gt;System.Runtime.InteropServices;
&lt;span style="color: blue;"&gt;using &lt;/span&gt;System.Text;
&lt;span style="color: blue;"&gt;using &lt;/span&gt;System.Xml;
&lt;span style="color: blue;"&gt;using &lt;/span&gt;System.Xml.Serialization;

&lt;span style="color: blue;"&gt;namespace &lt;span style="color: #000000;"&gt;WindowPlacementExample&lt;/span&gt;&lt;/span&gt;
{
    &lt;span style="color: green;"&gt;// RECT structure required by WINDOWPLACEMENT structure
    &lt;/span&gt;[&lt;span style="color: #2b91af;"&gt;Serializable&lt;/span&gt;]
    [&lt;span style="color: #2b91af;"&gt;StructLayout&lt;/span&gt;(&lt;span style="color: #2b91af;"&gt;LayoutKind&lt;/span&gt;.Sequential)]
    &lt;span style="color: blue;"&gt;public struct &lt;/span&gt;&lt;span style="color: #2b91af;"&gt;RECT
    &lt;/span&gt;{
        &lt;span style="color: blue;"&gt;public int &lt;/span&gt;Left;
        &lt;span style="color: blue;"&gt;public int &lt;/span&gt;Top;
        &lt;span style="color: blue;"&gt;public int &lt;/span&gt;Right;
        &lt;span style="color: blue;"&gt;public int &lt;/span&gt;Bottom;

        &lt;span style="color: blue;"&gt;public &lt;/span&gt;RECT(&lt;span style="color: blue;"&gt;int &lt;/span&gt;left, &lt;span style="color: blue;"&gt;int &lt;/span&gt;top, &lt;span style="color: blue;"&gt;int &lt;/span&gt;right, &lt;span style="color: blue;"&gt;int &lt;/span&gt;bottom)
        {
            &lt;span style="color: blue;"&gt;this&lt;/span&gt;.Left = left;
            &lt;span style="color: blue;"&gt;this&lt;/span&gt;.Top = top;
            &lt;span style="color: blue;"&gt;this&lt;/span&gt;.Right = right;
            &lt;span style="color: blue;"&gt;this&lt;/span&gt;.Bottom = bottom;
        }
    }

    &lt;span style="color: green;"&gt;// POINT structure required by WINDOWPLACEMENT structure
    &lt;/span&gt;[&lt;span style="color: #2b91af;"&gt;Serializable&lt;/span&gt;]
    [&lt;span style="color: #2b91af;"&gt;StructLayout&lt;/span&gt;(&lt;span style="color: #2b91af;"&gt;LayoutKind&lt;/span&gt;.Sequential)]
    &lt;span style="color: blue;"&gt;public struct &lt;/span&gt;&lt;span style="color: #2b91af;"&gt;POINT
    &lt;/span&gt;{
        &lt;span style="color: blue;"&gt;public int &lt;/span&gt;X;
        &lt;span style="color: blue;"&gt;public int &lt;/span&gt;Y;

        &lt;span style="color: blue;"&gt;public &lt;/span&gt;POINT(&lt;span style="color: blue;"&gt;int &lt;/span&gt;x, &lt;span style="color: blue;"&gt;int &lt;/span&gt;y)
        {
            &lt;span style="color: blue;"&gt;this&lt;/span&gt;.X = x;
            &lt;span style="color: blue;"&gt;this&lt;/span&gt;.Y = y;
        }
    }

    &lt;span style="color: green;"&gt;// WINDOWPLACEMENT stores the position, size, and state of a window
    &lt;/span&gt;[&lt;span style="color: #2b91af;"&gt;Serializable&lt;/span&gt;]
    [&lt;span style="color: #2b91af;"&gt;StructLayout&lt;/span&gt;(&lt;span style="color: #2b91af;"&gt;LayoutKind&lt;/span&gt;.Sequential)]
    &lt;span style="color: blue;"&gt;public struct &lt;/span&gt;&lt;span style="color: #2b91af;"&gt;WINDOWPLACEMENT
    &lt;/span&gt;{
        &lt;span style="color: blue;"&gt;public int &lt;/span&gt;length;
        &lt;span style="color: blue;"&gt;public int &lt;/span&gt;flags;
        &lt;span style="color: blue;"&gt;public int &lt;/span&gt;showCmd;
        &lt;span style="color: blue;"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af;"&gt;POINT &lt;/span&gt;minPosition;
        &lt;span style="color: blue;"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af;"&gt;POINT &lt;/span&gt;maxPosition;
        &lt;span style="color: blue;"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af;"&gt;RECT &lt;/span&gt;normalPosition;
    }

    &lt;span style="color: blue;"&gt;public static class &lt;/span&gt;&lt;span style="color: #2b91af;"&gt;WindowPlacement
    &lt;/span&gt;{
        &lt;span style="color: blue;"&gt;private static &lt;/span&gt;&lt;span style="color: #2b91af;"&gt;Encoding &lt;/span&gt;encoding = &lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af;"&gt;UTF8Encoding&lt;/span&gt;();
        &lt;span style="color: blue;"&gt;private static &lt;/span&gt;&lt;span style="color: #2b91af;"&gt;XmlSerializer &lt;/span&gt;serializer = &lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af;"&gt;XmlSerializer&lt;/span&gt;(&lt;span style="color: blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af;"&gt;WINDOWPLACEMENT&lt;/span&gt;));

        [&lt;span style="color: #2b91af;"&gt;DllImport&lt;/span&gt;(&lt;span style="color: #a31515;"&gt;"user32.dll"&lt;/span&gt;)]
        &lt;span style="color: blue;"&gt;private static extern bool &lt;/span&gt;SetWindowPlacement(&lt;span style="color: #2b91af;"&gt;IntPtr &lt;/span&gt;hWnd, [&lt;span style="color: #2b91af;"&gt;In&lt;/span&gt;] &lt;span style="color: blue;"&gt;ref &lt;/span&gt;&lt;span style="color: #2b91af;"&gt;WINDOWPLACEMENT &lt;/span&gt;lpwndpl);

        [&lt;span style="color: #2b91af;"&gt;DllImport&lt;/span&gt;(&lt;span style="color: #a31515;"&gt;"user32.dll"&lt;/span&gt;)]
        &lt;span style="color: blue;"&gt;private static extern bool &lt;/span&gt;GetWindowPlacement(&lt;span style="color: #2b91af;"&gt;IntPtr &lt;/span&gt;hWnd, &lt;span style="color: blue;"&gt;out &lt;/span&gt;&lt;span style="color: #2b91af;"&gt;WINDOWPLACEMENT &lt;/span&gt;lpwndpl);

        &lt;span style="color: blue;"&gt;private const int &lt;/span&gt;SW_SHOWNORMAL = 1;
        &lt;span style="color: blue;"&gt;private const int &lt;/span&gt;SW_SHOWMINIMIZED = 2;

        &lt;span style="color: blue;"&gt;public static void &lt;/span&gt;SetPlacement(&lt;span style="color: #2b91af;"&gt;IntPtr &lt;/span&gt;windowHandle, &lt;span style="color: blue;"&gt;string &lt;/span&gt;placementXml)
        {
            &lt;span style="color: blue;"&gt;if &lt;/span&gt;(&lt;span style="color: blue;"&gt;string&lt;/span&gt;.IsNullOrEmpty(placementXml))
            {
                &lt;span style="color: blue;"&gt;return&lt;/span&gt;;
            }

            &lt;span style="color: #2b91af;"&gt;WINDOWPLACEMENT &lt;/span&gt;placement;
            &lt;span style="color: blue;"&gt;byte&lt;/span&gt;[] xmlBytes = encoding.GetBytes(placementXml);

            &lt;span style="color: blue;"&gt;try
            &lt;/span&gt;{
                &lt;span style="color: blue;"&gt;using &lt;/span&gt;(&lt;span style="color: #2b91af;"&gt;MemoryStream &lt;/span&gt;memoryStream = &lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af;"&gt;MemoryStream&lt;/span&gt;(xmlBytes))
                {
                    placement = (&lt;span style="color: #2b91af;"&gt;WINDOWPLACEMENT&lt;/span&gt;)serializer.Deserialize(memoryStream);
                }

                placement.length = &lt;span style="color: #2b91af;"&gt;Marshal&lt;/span&gt;.SizeOf(&lt;span style="color: blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af;"&gt;WINDOWPLACEMENT&lt;/span&gt;));
                placement.flags = 0;
                placement.showCmd = (placement.showCmd == SW_SHOWMINIMIZED ? SW_SHOWNORMAL : placement.showCmd);
                SetWindowPlacement(windowHandle, &lt;span style="color: blue;"&gt;ref &lt;/span&gt;placement);
            }
            &lt;span style="color: blue;"&gt;catch &lt;/span&gt;(&lt;span style="color: #2b91af;"&gt;InvalidOperationException&lt;/span&gt;)
            {
                &lt;span style="color: green;"&gt;// Parsing placement XML failed. Fail silently.
            &lt;/span&gt;}
        }

        &lt;span style="color: blue;"&gt;public static string &lt;/span&gt;GetPlacement(&lt;span style="color: #2b91af;"&gt;IntPtr &lt;/span&gt;windowHandle)
        {
            &lt;span style="color: #2b91af;"&gt;WINDOWPLACEMENT &lt;/span&gt;placement = &lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af;"&gt;WINDOWPLACEMENT&lt;/span&gt;();
            GetWindowPlacement(windowHandle, &lt;span style="color: blue;"&gt;out &lt;/span&gt;placement);

            &lt;span style="color: blue;"&gt;using &lt;/span&gt;(&lt;span style="color: #2b91af;"&gt;MemoryStream &lt;/span&gt;memoryStream = &lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af;"&gt;MemoryStream&lt;/span&gt;())
            {
                &lt;span style="color: blue;"&gt;using &lt;/span&gt;(&lt;span style="color: #2b91af;"&gt;XmlTextWriter &lt;/span&gt;xmlTextWriter = &lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af;"&gt;XmlTextWriter&lt;/span&gt;(memoryStream, &lt;span style="color: #2b91af;"&gt;Encoding&lt;/span&gt;.UTF8))
                {
                    serializer.Serialize(xmlTextWriter, placement);
                    &lt;span style="color: blue;"&gt;byte&lt;/span&gt;[] xmlBytes = memoryStream.ToArray();
                    &lt;span style="color: blue;"&gt;return &lt;/span&gt;encoding.GetString(xmlBytes);
                }
            }
        }
    }
}&lt;/pre&gt;
&lt;p&gt;To get the placement of an existing window, you give it the native handle for the window, and get back a string of XML that represents the placement for the window. You save this string somewhere, then when the program starts back up again, apply it with SetPlacement. The above code works for both WinForms and WPF. And in both cases you can open your Properties/Settings.settings file and add a new setting to store the string:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/davidrickard/WindowsLiveWriter/SavingwindowsizeandlocationinWPFandWinFo_10F6C/image_2.png"&gt;&lt;img style="display: inline; border-width: 0px;" title="image" alt="image" src="http://blogs.msdn.com/blogfiles/davidrickard/WindowsLiveWriter/SavingwindowsizeandlocationinWPFandWinFo_10F6C/image_thumb.png" width="445" border="0" height="93" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;p&gt;This will store the window state locally, per-user. Of course you could also store the string wherever you wanted to.&lt;/p&gt;
&lt;p&gt;What I like about this approach is that the WindowPlacement class does the XML serialization for you and gives you a nice, tidy string containing all the placement data.&lt;/p&gt;
&lt;p&gt;But where in the program code should we hook in to save and re-apply the window placements? The answer is a bit different between WinForms and WPF.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;WPF:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;You might benefit by throwing a couple of extension methods on the WindowPlacement class to make things a bit easier:&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public static void &lt;/span&gt;SetPlacement(&lt;span style="color: blue;"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af;"&gt;Window &lt;/span&gt;window, &lt;span style="color: blue;"&gt;string &lt;/span&gt;placementXml)
{
    &lt;span style="color: #2b91af;"&gt;WindowPlacement&lt;/span&gt;.SetPlacement(&lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af;"&gt;WindowInteropHelper&lt;/span&gt;(window).Handle, placementXml);
}

&lt;span style="color: blue;"&gt;public static string &lt;/span&gt;GetPlacement(&lt;span style="color: blue;"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af;"&gt;Window &lt;/span&gt;window)
{
    &lt;span style="color: blue;"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af;"&gt;WindowPlacement&lt;/span&gt;.GetPlacement(&lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af;"&gt;WindowInteropHelper&lt;/span&gt;(window).Handle);
}&lt;/pre&gt;
&lt;p&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;To save the window placement, just handle the Closing event on the Window:&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;private void &lt;/span&gt;Window_Closing(&lt;span style="color: blue;"&gt;object &lt;/span&gt;sender, &lt;span style="color: #2b91af;"&gt;CancelEventArgs &lt;/span&gt;e)
{
    &lt;span style="color: #2b91af;"&gt;Settings&lt;/span&gt;.Default.MainWindowPlacement = &lt;span style="color: blue;"&gt;this&lt;/span&gt;.GetPlacement();
    &lt;span style="color: #2b91af;"&gt;Settings&lt;/span&gt;.Default.Save();
}&lt;/pre&gt;
&lt;p&gt;To restore, you&amp;rsquo;ll need to hook in on SourceInitialized:&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;protected override void &lt;/span&gt;OnSourceInitialized(&lt;span style="color: #2b91af;"&gt;EventArgs &lt;/span&gt;e)
{
    &lt;span style="color: blue;"&gt;base&lt;/span&gt;.OnSourceInitialized(e);
    &lt;span style="color: blue;"&gt;this&lt;/span&gt;.SetPlacement(&lt;span style="color: #2b91af;"&gt;Settings&lt;/span&gt;.Default.MainWindowPlacement);
}&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;WinForms:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;This one is a bit more straightforward. Save on the FormClosing event and restore the window state in the Load event handler. The Form&amp;rsquo;s native handle is accessible from its Handle property.&lt;/p&gt;
&lt;p&gt;Now we have a robust and relatively painless way of persisting window sizes and positions, and we only need to keep track of one string per window.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9975248" width="1" height="1"&gt;</description></item></channel></rss>