Windows 8 Task Manager

Fri, November 4, 2011, 08:47 PM under Windows

If you are a user of Task Manager (btw, make sure you've read my Task Manager shortcut tips), you must read the blog post on the overhaul coming to Task Manager in Windows 8 – coo stuff!

Also, long time readers of my blog will know that back in 2008 I wrote about Windows Vista and Windows 7 number_of_cores support, and in 2009 I shared a widely borrowed screenshot of Task Manager from one of our 128-core machines. So I was excited to just read on the Windows 8 blog that Windows 8 will support up to 640 cores. They shared a screenshot of a 160-core machine, so there goes my record ;-)


Links to C++ AMP and other content

Fri, September 16, 2011, 10:00 PM under GPGPU | Links | ParallelComputing | VisualStudio | Windows

A few links you may be interested in.


Support more than 64 cores from .NET code?

Fri, July 24, 2009, 05:26 PM under Windows
As you know by now, Windows 7 supports up to 256 logical processors (a 4-fold increase from previous versions). A few months ago I posted my screenshot of a system with 128 cores and reader kotsoft asked why the CPU utilization was at 50%.

The reason is that I was running a straightforward .NET 4 app that used TPL and the CLR 4 ThreadPool does not take advantage of more than 64 cores. Digging deeper reveals that there are certain new (native obviously) APIs that an application must use to go beyond the 64-core support and specifically the ones described here about processor groups – the CLR is not utilizing them in this release.

I wonder who will be the first to wrap these functions from managed code and show an example of their usage…

Windows 7 Task Manager screenshot

Mon, April 27, 2009, 10:59 PM under Windows
Previously I linked to a screenshot of 96 virtual processors and now I have access to a machine that tops that!

Count them:

Nothing else to share here, just a geek showing off ;-)

Internet Explorer 8 using Restart APIs to full potential

Thu, March 19, 2009, 11:49 AM under Windows
I have been playing with internal bits of Internet Explorer 8 for a while and it is pretty cool. Today the final version has shipped and you can download IE8 from the Microsoft site. To see the many cool enhancements I'd encourage you to watch the short videos (or at least just the Overview) on the dedicated IE8 videos page.

One of the things I like doing to new apps is crashing them. When a windows app crashes, I fully expect it to restart and restore the state it had before it died. I ranted in detail on that front in an older post of mine 2 years ago.

Internet Explorer 8 finally delivers on my request. This is what I see after I crash it and it restarts:

Love it!

Windows 7 and Server 2008 R2

Fri, January 9, 2009, 12:01 AM under Windows
The Beta of Windows 7 and Windows Server 2008 R2 are available to download. This is the release which supports up to 256 cores, and you can see a screenshot of a machine running the OS with 96 cores (!) on Mike's blog.

How Many Cores does Windows Support?

Mon, November 17, 2008, 12:38 PM under Windows
At external and internal parallel programming sessions I have on one of my slides a screenshot of the Task Manager window showing 64 cores (!). There is always someone in the audience that didn’t know Windows can support that many. To see the screenshot for yourself, visit MarkRuss's blog post.

Even if you knew that, maybe you didn’t know that in the next version we are supporting 4 times as many:
"In Windows Server 2008 R2, we have built in support for up to 256 logical processors, which will allow our customers to more fully exploit today’s powerful CPUs,"
To get more info on that and the other Windows 7 enhancements for the manycore era (e.g. UMS), watch this interview with Mark Russinovich

Session 0 Isolation

Fri, March 7, 2008, 03:58 AM under Windows | Vista | WindowsServer2008
In the latest issue of the MSDN Flash we introduced 2 new features: a poll (you'll see the results in the next issue) and the ability to have a non-MS person write the 500 word article. Kenny kindly accepted the challenge and he wrote a great article on a security topic that may affect your code on Windows Vista and Windows Server 2008. Read it here (scroll down).

Virtualization in WS2K8

Fri, February 1, 2008, 03:20 AM under Windows | WindowsServer2008
Virtualization is going to be (if it isn't already) a huge topic for anyone involved in the IT industry. I know that IT Pros are very excited about Microsoft's offering with Windows Server 2008 but I wasn't sure how many developers have at least a high level appreciation of what virtualization is and how Hyper-V fits into the big picture.

To find out, I would encourage you to spend some time browsing the numerous links and content on these sites:
1. Microsoft Virtualization.
2. Windows Server 2008 Hyper-V.
3. Also recently, Bob Muglia sent this executive email on virtualization, should you need something to forward to your manager.
4. Finally, see this dedicated blog.

If you have access to the TechEd Europe IT Forum 2007 post-conference recordings, there are 4 sessions that I recommend: MGT323, SVR307, SVR320 and SVR322. I watched those collective 300 minutes and (combined with what floated my boat from the other links above) distilled the most interesting bits into a 15'-20' section of my Windows Server 2008 developer session. It is from those 4 sessions that I stole the slides I used ;-). You can find them in this powerpoint deck (36-58 inclusive).

Native Threading APIs in Windows Server 2008

Tue, January 29, 2008, 11:35 AM under Windows | Vista | WindowsServer2008
On 3 recent events I spent 20' talking about the new native threading APIs in Windows Vista and Windows Server 2008. Here are resources as promised.

1. Thread Pool – re-architected native ThreadPool that amongst other things allows multiple pools per process.

2. One-Time Initialization – think singletons for the native world with an interesting option of asynchronous initialization.

3. Slim Reader/Writer Lock (SRW) – finally a reader writer lock out of the box for native devs.

4. Condition Variables – addresses scenarios such as the classic producer/consumer pattern in a more efficient way than previous techniques.

5. Thread Ordering Service (TOS) – an interesting service that I cannot find a compelling use case for. If you've got one, let me know!

6. Wait Chain Traversal (WCT) – aids in programmatically debugging deadlocks and hangs.

The links above point to the MSDN documentation where you can click further to read the API descriptions and click further to see code examples. In addition, the MSDN Magazine has 3 articles that describe all of the above (except for the TOS):
- June 2007 – Describes Condition vars, SRW, and One-Time Init. Don't let the title fool you, these are even more applicable with the release of Windows Server 2008.
- July 2007 – Describes usage of the WCT from unsafe C# code to create a utility.
- October 2007 – Describes the New Thread Pool APIs.

Lastly, I have created some slides for the above. Nothing fancy, just very boring bullets with lots of text and API signatures with nothing additional than what you can find in the links above. Their only use is if you need to talk about this topic and cannot be bothered to create your own from scratch, you can use mine as a starting point. See slides 8-22 inclusive in this deck.

Code signing

Fri, December 21, 2007, 05:21 AM under Windows | Vista
In all my Vista talks I emphasize that with Windows Vista, applications must be signed. Not just for UAC, but for other areas as well (e.g. WER) and it is an actual logo certification requirement. If you haven't dabbled with code signing before I guess it implies that you don’t work for a large enterprise. In that case, head over here for an end-to-end "how to" on code signing.

SystemIcons.Shield

Sat, December 15, 2007, 06:42 AM under dotNET | Windows | Vista | UAC
Seasoned Windows Forms developers will be familiar with the System.Drawing.SystemIcons class that has a bunch of properties returning standard system icons. For example, if you throw on a form a picturebox and a button with its event handler the following code shows how you can take advantage of SystemIcons:
void button1_Click(System.Object sender, System.EventArgs e)
{
// use Error
pictureBox1.Image = Bitmap.FromHicon(SystemIcons.Error.Handle);

// use Warning
this.Icon = SystemIcons.Warning;

// use Information
int h = button1.ClientSize.Height / 2;
Icon ico = new Icon(SystemIcons.Information, h, h);
Bitmap bitmap1 = Bitmap.FromHicon(ico.Handle);
button1.Image = bitmap1;
button1.ImageAlign = ContentAlignment.MiddleLeft;
}
With Service Pack 1 of .NET Framework v2.0 we get a new member of that class: SystemIcons.Shield. So, if you are on Windows Vista and you are working with User Account Control, you may find it a useful icon to use (for example on a menu).

Below is a screenshot of what the code above looks like side by side, before clicking the button and after. The screenshot at the bottom is after replacing the 3 icons with shield:

VS2008 supports Restart Manager

Tue, August 14, 2007, 03:15 AM under Windows | Vista | Orcas | VisualStudio
Two of my favourite new APIs of Windows Vista are: restart/recovery and Restart Manager.

I mentioned in passing that Orcas March CTP supported the restart API. I haven't had a chance to test if that area has been improved because I can't get Visual Studio 2008 Beta 2 to crash! If you have a repro case that crashes Beta 2, please let me know how.

How about Restart Manager support by Visual Studio 2008? I had tested this with Beta 1 and the answer was "no". Tested it with VS2008 Beta 2 and the answer is a resounding "yes". Not only it supports RM for being gently shutdown, but it actually does the right thing when it is restarted which is to auto open the solution you had open even down to the file you were viewing! If you had a file unsaved, it will prompt you on restart if you'd like to recover:


To see the RM functionality with VS2008 in action on your Vista machine running Beta 2, one easy way is to download my Vista demos, locate the project in the folder "RestartManagerSimulator", build it and then execute from the Debug folder the executable: RestartmanagerSimulator.exe. You should see an app that looks like this. In the textbox enter "devenv" (without the quotes) and hit the buttons in order: "Supports Restart?", "Register" and "Shutdown". Wait while that operation completes and Visual Studio exits. Then click on "Restart" and watch the magic happen ;-)

Vista updates

Tue, August 7, 2007, 02:44 PM under Windows | Vista
Both of them installed fine for me (screenshot). If you want performance, compatibility and reliability go get this one and that one.

Vista ComboBox

Fri, July 20, 2007, 05:30 AM under Windows | Vista
Over time I've talked about XP and Vista textbox cue banners (and even implemented a version for Windows Mobile), but I hadn't realised they can be used for Vista combo boxes as well! The clue came via Kenny's MSDN mag article (includes many other features for the C++ Vista developer).

So all I had to do was the simple translation to managed code, which involves one line of code (assuming you have a combobox on your form with a few items to select and none set as selected):
SendMessage(comboBox1.Handle, 0x1703, 0, "Choose"); //CB_SETCUEBANNER

From left to right in the image above: Before the API call, before the call and the drop down open, After the API call, after the call with the drop down open. Of course once you select a real value from the combobox you do not see the cue banner (e.g. "Choose") again.

FYI, I actually found that any value for the two ComboBox properties DropDownStyle and FlatStyle worked, and the ones in the image above are DropDownList and System respectively.

Sidebar shortcuts

Tue, July 17, 2007, 06:36 AM under Windows | Vista
You know of course that WindowsKey+D shows the desktop and this includes hiding the Sidebar. If you want to show the desktop but still have the Sidebar (and any floating gadgets) visible then hit Win+M. If at any point you need to bring on top the Sidebar and gadgets regardless of what other windows are showing, hit Win+Spacebar.

Now the new ones I only learnt this week (shame on me I know): Win+G will cycle through the gadgets and while a gadget is selected, Shift+F10 will bring up the context menu. Am I missing any other relevant shortcuts?

Contacts.Net

Mon, July 16, 2007, 04:26 AM under Windows | Vista
It looks like the number of managed wrappers to the 7000 new native APIs that Windows Vista introduced is growing. I recently discovered a library that wraps the COM API for working with Vista's Contacts. To download it (inc. the source code) and for other relevant links, please visit the codeplex project.

Found via uberdemo.

Download my Vista demos

Sat, June 23, 2007, 06:07 AM under Windows | Vista
Last November I made a TOC post that linked to all my work on Vista-only features for Managed Developers. I have updated that blog post today so I strongly suggest you revisit it if the topic interests you and you want content, videos and slides.

By following and reading those links you can recreate every single one of my demos – trust me, that is the best way to learn this stuff! You should also note that any demo I show in presentations is a DEMO; it is not real production-ready code by any stretch of imagination. Also many of my demos won't make any sense to someone that has not seen me present them (e.g. at UK MSDN events, Tech Ed, UK Vista launch, DevDays...) and some of them are incomplete since I do the coding on the fly while others will not work if you don't install their dependencies as described in my sessions. My demo projects target .NET Framework 2.0 from C# and the project/solution format is for Visual Studio 2008. You could create VS2005 projects and add the code files from my projects if you don't have VS2008 Beta 1.

So, with those caveats in place and by popular demand, you can now download my demo code here. Enjoy!

Sidebar + SideShow = Love

Fri, June 22, 2007, 01:35 AM under Windows | Vista | SideShow
In the past I have introduced Sidebar gadgets and have made a quite few blog posts on SideShow. What I've not done here is talk about the integration between these two. In this blog entry I'll assume you are familiar with both of them independently.

HOW:
The integration is about being able to send content from your Sidebar gadget to SideShow-enabled devices. Effectively, the SideShow gadget(s) running on Windows *is* the Sidebar process. So how do you SideShow-enable your Sidebar gadget? You add a bit to your manifest and the remainder modifications are all in javascript calling the SideShow methods of the Sidebar API:

1. Add an icon for SideShow to your Sidebar gadget manifest. In your gadget.xml file you already have an icon element under an icons element which is under the gadget element. You need to add another element named ico that points to your SideShow icon i.e.
   <icons>
<icon height="48" width="48" src="daniel.PNG" />
<ico src="SSnotification1.ico"/>
</icons>

2. Set a friendly name. Somewhere in your javascript make the following method call:
var friendName = "danielmoth.com"; //your data
System.Gadget.SideShow.setFriendlyName(friendName);
3. Add glance content. Whenever you want to update the glance data, make this call:
var glance = "Hello from Sidebar"; //your data
System.Gadget.SideShow.addText(0, glance);
At this point on your SideShow device you have something like this:

4. If you want to send SCF pages, use the same method as above, this time changing the id (first argument) as appropriate and making the 2nd argument hold the XML, e.g.
var scfXmlcontent = "<body><menu id='1' title='My menu'><item target='2'>I am a menu</item></menu></body>";
System.Gadget.SideShow.addText(1, scfXmlcontent);
So, on your previous screenshot if you now click on the SideShow's OK button you'll get the following:

Clearly, if you select the menu item then you'll get a "Page not found" message because we haven't send any other page with an id=2. I leave that as an exercise to you.

NOTES:
Of course, it would be great if whatever you render on your Sidebar gadget automatically got sent to the SideShow device but as you see above, that is not the case. However, the crucial part of building gadgets in general is getting the content that you want to show: you only need fetch that once and then you just need to package it twice (html for Sidebar and SCF for SideShow).

Note that if you want to send images that you reference by id in your SCF pages, then you must use the addImage API. When you visit the APIs, ignore their advice to check for the enabled method because it apparently always returns true. Also note that when you want to update the same content id, it is best that you call the remove method first and the send down the new content corresponding to the id. You should also not bother with notifications or events for combined gadgets, since the applicationEvent is non-functioning.

DOWNLOAD:
Should you wish to play with the simple sample I described here and you are too lazy to type it yourself, download this ZIP on your Vista machine and then execute the daniel.gadget inside it. To see a fully fledged proper gadget and not the Hello World demo I created, download the StocksPlus combined gadget (it is the Stocks gadget you have in your box, enhanced to support SideShow). Whichever gadget your download, first make sure the SideShow Simulator is running already! Enjoy :)

Vista ProgressBar

Fri, June 8, 2007, 05:46 AM under Windows | Vista
While prepping for an event in Amsterdam next week, I am revisiting all my content from last year to do with Vista for managed developers. A very small part of the presentation is showing the WinForms controls and what additional things you can do with them in Vista such as the TextBox cue banner, commandlink button, treeviewvista, adding shield to clickable controls etc.

It occurred to me that I never looked at the ProgressBar control. In Vista, in addition to NORMAL (green), the control can be in a state of PAUSE (yellow) and ERROR (red). However, the managed ProgressBar control does not expose a managed way of controlling that. Once again, PInvoke to the rescue:
// Assuming a Form1 with 3 ProgressBar controls
private void Form1_Load(object sender, EventArgs e)
{
SendMessage(progressBar2.Handle,
0x400 + 16, //WM_USER + PBM_SETSTATE
0x0003, //PBST_PAUSED
0);

SendMessage(progressBar3.Handle,
0x400 + 16, //WM_USER + PBM_SETSTATE
0x0002, //PBST_ERROR
0);
}

[DllImport("user32.dll", CharSet = CharSet.Unicode)]
static extern uint SendMessage(IntPtr hWnd,
uint Msg,
uint wParam,
uint lParam);


For a more complete reusable wrapper of the ProgressBar (inc. some other features that I have not covered) check out the code from the VistaControls project on codeplex.

Winforms 1 - WPF 0

Wed, May 16, 2007, 09:11 PM under dotNET | Windows | Vista | Orcas
Oh, how happy I was when Orcas started using the Vista CommonFileDialog. Oh, how pissed off I get when applications on Vista still use the old legacy dialog. One of the applications I use a lot is Reflector and for a while I've been nagging Lutz on IM and email to make Reflector use the new OpenFileDialog, but nothing came of my harassment. Until recently when I noticed that Reflector indeed started showing me the new dialog so I thanked Lutz for finally listening. His reply was that he wasn't aware of it and he had changed nothing other than it now forces it to run against 2.0.50727 using a config file. That put me on a hunt!

The result of the hunt was that with the "Orcas" update of v2.0.50727 (remember how I explained this a few hours ago) the System.Windows.Forms.OpenFileDialog has had an internal implementation change that makes it detect if it is on Vista and puts the correct dialog up, rather than the legacy one (on a legacy OS like XP, it will show the old dialog of course). Using reflector, the place to look is FileDialog.RunDialogVista called by FileDialog.RunDialog which is called by CommonDialog.ShowDialog. Great news!

So I then wanted to see if the WPF version has also been updated, in which case half of VistaBridge would be obsolete (the TaskDialog half would still be useful of course). Unfortunately, the WPF version of OpenFileDialog (residing in Microsoft.Win32 namespace in the PresentationFramework.dll) has not been updated. I am confident that it will happen by RTM, but in the meantime from your WPF projects you can reference the System.Windows.Forms.dll and use its Open/SaveFileDialog instead.

PerformanceData

Tue, May 15, 2007, 04:10 PM under dotNET | Windows | Vista | Orcas
One of the namespaces in the new System.Core.dll is System.Diagnostics.PerformanceData. It is a set of classes that wrap a new set of performance counter APIs (in Advapi32.dll) that are applicable only to Vista and higher. Here is a class diagram followed by an explanation:

Rather than actual code, here are the steps for working with the set of classes above.
1. Create a CounterSet object specifying the CounterSetInstanceType
2. On this instance, call AddCounter specifying an integer id and a CounterType (plus optionally a name) [repeat this step as desired]
3. Once done repeating step 2, call CreateCounterSetInstance to obtain a CounterSetInstance object.
4. On the object of step 3, via its Counters property get an instance of the collection object: CounterSetInstanceCounterDataSet
5. From this collection, retireve the CounterData objects either via the integer id or by name
6. Only one long Value property on the CounterData objects to tell you what you are after

In case you are wondering, step 1 above wraps PerfStartProvider and step 3 wraps three APIs in sequence: PerfSetCounterSetInfo, PerfCreateInstance and PerfSetCounterRefValue. If you look at the native signatures and the "cute" structures they expect you to setup, then you'll realise why it has been wrapped for us :-)

Programmatically determine if UAC is enabled

Thu, April 26, 2007, 07:38 PM under Windows | Vista | UAC
This is a question I get often:
"How can I determine if User Account Control is on or off via code?"
The answer I always give:
"You are asking the wrong question. Who cares?"
The point being that, regardless of whether the user has turned off UAC or not, your application should still be partitioned and work correctly for both admins and non-admin users. It is irrelevant if UAC is on or off. You should still display the shields, you should still gracefully fail if the user is not an admin (same as you would if the elevation prompt came up and the user cancelled, same as you should if you were running on XP). The academic answer to the original question is that you can read it from the registry (much like the built-in Security Centre does). Since there is no genuine requirement to know this stuff from code, there is no API for it.

So the only question to answer programmatically is how to know if the user has admin rights. I have shown how to do this before but here goes again:
 // using System.Security.Principle;
private bool IsAdmin()
{
WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal p = new WindowsPrincipal(id);

return p.IsInRole("Administrators");
}
I have read blogs where others get further information regarding elevation about the user's account by pinvoking native APIs, but again, I remain totally unconvinced about that need. Your app shouldn't care about anything else: all that matters is if the user has admin rights at the moment your admin code is about to execute, nothing else.

If you disagree and think you have a genuine reason for knowing more than what I describe above, then please post your scenario to the relevant forum linked to from here.

VirtualSideShow

Wed, April 25, 2007, 11:06 AM under Windows | Vista | SideShow
At some point I must find time to continue my series of blog posts on the Windows SideShow technology that ships with Vista. But until then, if you've wanted to play with this stuff but couldn't be bothered to download the Windows SDK (shame on you btw!), now you have the option of downloading the Device Simulator as standalone (and it is a newer version too!). Go get it.

UAC Elevation with COM

Thu, April 19, 2007, 01:05 PM under Windows | Vista | UAC
You've probably read my posts on UAC (tip: read bottom up), and in my talks I always explain how to factor out into separate processes any admin functionality.

What I've never explained is how to factor into out-of-proc COM objects the admin functionality. Christoph has explained that on his blog and has done it all in managed code no less! Check his posts out starting here (and follow his links for the rest).

Bridge in Glidepath

Thu, April 19, 2007, 12:27 PM under Windows | Vista
By now you all know about the VistaBridge sample that is part of the Windows SDK. I hope you also know about Project Glidepath. Apparently, the guys behind glidepath thought it was too much effort for a developer to have to type code that simply sets properties like the code shown here, so they created a package where you simply make selections with the mouse and the code gets spat out for you!

Definitely worth watching the 5 minute screencast (follow their link).

Vista native stuff for WPF

Fri, March 30, 2007, 11:11 AM under Vista | Windows
When I do my talk showing how to call Vista-only native APIs to enhance your Windows Forms applications on Vista, occasionally someone asks about achieving the same in Windows Presentation Foundation (WPF). My answer is always the same of course: "WPF does not include any Vista-only APIs so you still have to pinvoke for the features that I demonstrate."

For example, many features rely on overriding the WndProc method to hook into the main message loop and deal with some windows message (WM_):
  protected override void WndProc(ref Message m)
{
// e.g. deal with message for
// composition changed, power state notification, restart manager aware etc
}
In WPF you can achieve that with code like this:
       void Window1_Loaded(object sender, RoutedEventArgs e)
{
source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
source.AddHook(new HwndSourceHook(WndProc));
}

private static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
// TODO handle WM_
}
While the previous statement/reply/example is true, some of the things I show in my talk rely on using a control's handle. For example, adding a shield to a button (for UAC), the new button style known as CommandLink, TextBox cue banner, Vista TreeView etc. In those cases, for WPF you can't use pinvoke to SendMessage or subclass the control (Get/SetWindowLong etc) since the WPF controls are drawn from scratch. Instead, you have to manually draw the effect you are after. The Windows SDK has an example of a CommandLink fully drawn for WPF but I couldn't see any of the others (e.g. a button with a shield) so this is a great opportunity for a WPF developer to flex their creativity muscles and create the Vista control behaviours/appearances for WPF (since pinvoking doesn't help there). Be sure to let me know if you get round to implementing anything like that in the public domain...

Photoshop Preview Handler

Fri, March 30, 2007, 09:51 AM under Windows | Vista
Regular readers will recall my blog entries about managed preview handlers on Vista. Rajesh dropped me a comment pointing to his codeproject article. Let him know what you think.

One of the aspects I like about his preview handler is that it uses a tooltip to offer more info. Regardless of how easy/hard the visualization of a file is, adding a tooltip for extra info is a simple yet awesome idea IMO - good job!

Please use the Restart API to its full potential

Tue, March 27, 2007, 02:10 PM under Windows | Vista
I've been meaning to rant about this and Sahil gave me the incentive with his wish list for IE8 and Vista.

The 2nd wish item on his list for Internet Explorer is:
"When IE crashes, there should be an option for it to restore state, i.e. re-open the tabs I had opened when it crashed."
IE7 has crashed on me in the past and I do recall the behaviour that Sahil is referring to which, for those of you not running Vista, is that IE7 restarts so you don't have to restart it yourself :-). Cool, but IE7 restarts with the default home page(s), instead of opening my last browsed tabs and that is not cool. The reason this really gets to me is that I know it is so darn easy to implement the feature!

In fact, the Restart API is an area where unfortunately I am seeing a pattern of our product teams taking advantage of only half the feature (the restart bit, without the restoring state bit). The Visual Studio Codename Orcas March CTP is an application that made me smile in a very positive way when it crashed on Vista (where it is not supported) and I observed that it restarted after sending the error report. But again to my dismay, it simply restarted and left it at that. Hopefully by the time it ships, the team will implement the rest of the feature so when it restarts it also attempts to open the last solution I was working on.

Now, there is a (weak) argument either of the teams above can make that goes as follows: "If when we restart, after a crash, we try to restore the last opened tab/project, then we run the risk of ending up in a cyclical restart". This is a weak argument for two reasons:
1. The API can protect you against cyclical restarts (look at the 2nd parameter of the function from the link above and also the 60 second rule I describe in the video linked above)
2. I would expect dialog that has words to this effect: "We are sorry you experienced an issue with this application, an error report has been sent. Would you like to open the last solution/web page you were looking at? NOTE: This may cause the application to crash again!". And after displaying that message, if the user chooses to continue and they crash again, the next time don't put up the dialog and don't try to restore state.

This isn't rocket science. We have a fantastic feature in Vista; the teams have started to take advantage of it but just falling short in the end. IE7 has shipped of course, but I remain hopeful for "Orcas" to be smarter about this by RTM...

What a great way to leverage the Restart Manager

Wed, March 14, 2007, 03:50 PM under Windows | Vista
While I have previously described Restart Manager, I never thought to use it in this cool way even though the question definitely is something I have asked myself in the past! Keep reading...
Question: When my application attempts to access a file, I get access-denied errors because the file is in use by another application. In the past, I've used tools from Sysinternals (microsoft.com/technet/sysinternals) to figure out what that other application is, but I'd like to be able to discover this programmatically from within my application. Is there a way to programmatically determine what processes are currently using a specific file?

Answer: Stephen to the rescue!

VS2005 SP1 Update for Vista

Tue, March 6, 2007, 03:34 PM under Windows | Vista
Following the SP1 for VS2005, the update for Windows Vista is now also available. Get it here (especially if you are doing web development on Vista).

This is what my VS about box looks like after I installed it:


Also see Soma's relevant Q&A.

VS "Orcas" uses the new CommonFileDialog

Thu, March 1, 2007, 05:21 AM under Windows | Vista | Orcas | VisualStudio
Whenever I see an application on Vista that shows the old file dialog, I cringe (sorry, it is true). So given that I "live" in VS2005, it is the one that irritates me the most every day in that respect. It is easy to show it from native code and I have talked about the managed wrapper in VistaBridge before.

I've been waiting for a VS "Orcas" build that uses the new CommonOpenFileDialog when running on Vista and the March CTP does just that. All I can say is "WOO HOO".

Vista week on Channel9

Wed, February 28, 2007, 04:23 AM under Windows | Vista
More Vista content added to channel9 throughout the week. Watch it here.

Windows Vista Sidebar Gadget articles

Mon, February 5, 2007, 03:03 PM under Windows | Vista
Out of all the work I’ve done over the past year, I get the most “thank you” notes for the screencast introducing Sidebar and gadgets. Many of the emails I receive include a request for more info on Sidebar gadget development.

In addition to the ones at the end of my Sidebar blog entry (in FAQ format), I usually point to two other articles, included here for future reference:
1. OdeToCode article.
2. UKStudentzine article (from a student on our team :)).

Lastly, I received an email from Danny Espinoza asking me to try their product. Even though the description looks interesting, I don’t have the time right now to play with it; maybe someone reading my blog will want to try out their widget converter.

For Sidebar gadget support questions, please use the dedicated forum.

More Preview Handlers

Tue, January 30, 2007, 05:27 PM under Windows | Vista
Remember the awesome Managed Preview Handler Framework for Vista and Outlook? Visit the author’s blog to download a Preview Handler Association editor.

I also found a preview handler, written with the framework, which is for code file extensions such as .cs, .vb, .js and .sql (link to download here).

Given that the visual effect is best described with a video, I’ve recorded a screencast on the topic.

After recording the video I came up with a slightly more useful preview handler than the one I showed there. How many times have you wanted to quickly extract the FullName or specifically the PublicKeyToken from a strong-named assembly? So I thought I’d write a managed preview handler that works for managed DLLs and shows some quick info when you select the file in explorer as the following screenshot shows:


Like the demo preview handler shown in the screencast, only one method has real code and I am sure you can imagine what it looks like... and if not, get it here (demoware).

...and remember that preview handlers also work in Outlook 2007... I guess that is what they mean when they say "better together" ;-)

Windows Vista Ultimate Extras

Tue, January 30, 2007, 03:19 AM under Windows | Vista
With Windows Vista now available for everyone, 2-3 downloads are available for those running the Ultimate edition (as well as some other updates for everyone :-)).

This is what my Windows Update screen looked like today:

SideShow designer: ISV opportunity

Thu, January 18, 2007, 04:20 AM under Windows | Vista | SideShow
I am really pleased that Scott is jumping on the SideShow train :-)

Windows SideShow provides an opportunity for every manufacturer that has a device with a screen on it to SideShow-enable it. It also provides an opportunity for all application developers to extend the reach of their application by either directly calling the SideShow API from their existing app to send content to SideShow-compatible displays, or to write a new non-UI process (a SideShow gadget) that sends the content.

There is another opportunity here for ISVs. Provide a graphical designer for generating SCF, which application developers can then easily send down to the devices. Crafting SCF by hand or using the managed API’s Scf class is trivial but still not as smooth as using a graphical designer (a bit like designing Windows Forms without the designer or even closer a bit like crafting XAML by hand without "Sparkle"/"Cider").

So what are you waiting for? The schema is there, the elements (think controls) have only a few attributes (think properties) and there can only be a single element/control per row/line... show me what you can do!

UPDATE: The Microsoft.SideShow.dll (written by Jeffrey Richter) that I have been using in all my posts is now publicly available. Details here :-)

TreeViewVista

Wed, January 17, 2007, 05:28 PM under Windows | Vista
In an older post I highlighted one of the changes in the TreeView control in Vista’s explorer:
"...the treeview has no horizontal scrollbar at the bottom and scrolling happens for you automatically as you select nodes that are not fully visible and as you mouse over around..."
I then offered some code that makes the System.Windows.Forms.TreeView control behave the same way.

If you take a further look at the explorer TreeView you’ll notice that in addition to the autoscroll functionality previously described, there are also some aesthetic changes:
1. The selected TreeNode has a highlight rectangle but it is not the heavy blue that it was on legacy versions of Windows.
2. When hovering over non-selected TreeNodes, the node under the mouse also gets a very light blue rectangle.
3. Rather than ‘plus’ and ‘minus’ signs before each node (used for expanding/collapsing) it has some small triangles (filled with black, empty or highlighted with blue).

E.g. in the following picture the “inetpub” folder is highlighted while my mouse is over the “logs” folder:


So I was looking at how I can make my managed TreeView have the same feel and look. The answer is in the Vista MSDN forums: you have to call SetWindowTheme API from the uxtheme.dll as follows:
SetWindowTheme(treeView1.Handle, "explorer", null);

As an aside, you can use this exact code with the ListView control as well :-)

Note that for the managed TreeView you also have to set to true the HotTracking property (and for identical look, to false the ShowLines property).

So, next thing I noticed is that the explorer TreeView also auto hides the +/- replacements i.e. it auto hides the little triangles. It was easier finding out how to achieve that since I had already seen a list of new Vista TreeView constants which is where the inspiration for the blog entry on TVS_EX_AUTOHSCROLL came from. The answer is to add to the TreeView's extended style the TVS_EX_FADEINOUTEXPANDOS:
NativeMethods.SendMessage(treeView1.Handle,
NativeMethods.TVM_SETEXTENDEDSTYLE, 0,
NativeMethods.TVS_EX_FADEINOUTEXPANDOS);
...of course to add the style rather than just set it, first you have to retrieve the existing style and then bitwise OR it with the TVS_EX_FADEINOUTEXPANDOS style.

I have updated the two code files, which I posted last time, to incorporate these additions and you can get them from the same place: NativeMethods.cs and TreeViewVista.cs (the comments in the code are self-explanatory I hope).

Finally, note that you can pick and choose which feature you want. For example Windows Mail on Vista clearly sets the “explorer” theme (and HotTracking=true and ShowLines=false), but does not set the extended styles at all (so no auto-fading and no auto-scrolling)...

SideShow devices

Mon, January 8, 2007, 10:14 AM under Windows | Vista | SideShow
Just before leaving for CES, Dan Polivy recorded a short video for on10 showing off 8 SideShow-compatible devices: Asus laptop, LG Z1-p laptop, credit card companion device, remote controls from 3 different manufacturers and Logitech keyboard & speakers!

As always with cool gadgets words are not enough so check out the video and drool :-)

I wonder if the guy behind SideShowDevices will be posting pictures of all these soon...

UPDATE: Also spotted at CES, wearable SideShow device (thanks Keeron Modi for the heads up).

Best of "The Moth" 2006

Mon, January 1, 2007, 06:56 AM under dotNET | MobileAndEmbedded | Windows | Vista | Links
Exactly two years ago on New Year's day, I wrote the Best of "The Moth" 2004 blog enrty where I picked my favorite blog entries out of 96 posts. Exactly one year ago I had to choose from 151 posts to find the ones I thought were the best in terms of content and the result was the Best of "The Moth" 2005.

The year of 2006 I made 142 blog entries and below are a select few. Happy New Year!

01. I didn't have a chance to play with it as much as I wanted to, but with very little public info available, this blog served it well: .NET Micro Framework, its product sheet and other NETMF links.

02. Recognising an idiom of the using statement.

03. A cute desktop feature implemented for the Windows Mobile/WinCE platform in a reusable NETCF control: TextBox cue banner.

04. A picture is worth a 100 words and a video is... a whole bunch of pictures! Check mine out following the instructions here for my nuggets.

05. A comprehensive collection of links for Windows Workflow Foundation (WF).

06. I collected the links to my 9 blog posts on sharing assets between desktop and mobile platforms in one place. Follow the numbered links.

07. The most controversial feature of Windows Vista is something every developer must understand: User Account Control.

08. One of Vista's features is becoming my obsession and that is SideShow. My series of SideShow gadgets blog posts will continue in 2007 and so far you can read parts one, two, three, four and five.

09. I spent 6 months last year focusing almost entirely on Vista developer features that are new and that are *not* part of NetFx3. I have catalogued my blogging & screencasting efforts in a large collection of links to content that supports my speaking engagements on Vista. IMO this blog post alone could have been the best of "The Moth" this year:
Vista-only features for the managed developer.
Stay tuned in 2007 via one of the subscribe options on the left :-)

SideShow notifications and events

Fri, December 29, 2006, 08:44 PM under Windows | Vista | SideShow
When I introduced the SideShow gadget fundamentals, I listed 3 types of communication between the gadget running on the PC and the SideShow-compatible device. You know how to design your SCF content and then download it via the managed API. Here I will introduce notifications and events.

Notification
Sending a notification down to the device takes one line of code, given that you already have a ScfSideShowGadget reference as described before:
Icon ico = new Icon(@"C:\Users\Public\Pictures\SideShow\SSnotification.ico");
g.ShowNotification(
100, // unique content id
"some caption", // caption
"some message", // body
ico, // icon to appear on the far right of the body
TimeSpan.FromSecondss(30)); // timeout interval
Executing the above will result in the behaviour captured below on the SideShow simulator:

The notification will time out after the timeout period specified or the user can manually dismiss it with the ENTER button or, finally, you can programmatically dismiss a notification by its id e.g. g.RevokeNotification(100); or a more brutal approach g.RevokeAllNotifications;

Events
There are 9 events that you can handle programmatically on the PC-side while the user performs actions. The following code shows hooking up to them
g.AllDevicesRemoved += new EventHandler(g_AllDevicesRemoved);
g.ContentMissing += new EventHandler <ContentMissingEventArgs> (g_ContentMissing);
g.ContentNavigate += new EventHandler <ContentNavigateEventArgs> (g_ContentNavigate);
g.ContextMenuSelect += new EventHandler <ContextMenuSelectEventArgs> (g_ContextMenuSelect);
g.DeviceAdded += new EventHandler <DeviceCapabilityEventArgs> (g_DeviceAdded);
g.DeviceRemoved += new EventHandler <DeviceCapabilityEventArgs> (g_DeviceRemoved);
g.GadgetEnter += new EventHandler(g_GadgetEnter);
g.GadgetExit += new EventHandler(g_GadgetExit);
g.MenuSelect += new EventHandler <MenuSelectEventArgs>(g_MenuSelect);
- GadgetEnter, GadgetExit when the user navigates from the glance data page (id=0) to the SCF pages and back.
- DeviceAdded, DeviceRemoved, AllDevicesRemoved when SideShow-compatible device connect or disconnect from this gadget.
- MenuSelect, ContextMenuSelect when the user selects one of your menus or opens your contextmenus.
- ContentNavigate every time the user traverses from one SCF page to another.
- ContentMissing if a user action results in a request for a content id that is not on the device.

The event handler method signatures for these follow the standard .NET pattern of having two parameters. The first being the sender object and the second being a type that inherits from EventArgs. The following class diagram shows the EventArgs classes with their members so you can get an idea of the information you receive with each event mentioned above:


Stay tuned on this blog for more on SideShow gadget development in the new year ;-)

Writing managed control panel items

Fri, December 22, 2006, 09:36 AM under Windows | Vista
In the past, if you had to develop control panel items you would start thinking about .cpl files. With Windows Vista, there seems to be a tendency to take advantage of the new ability to create them in separate executables! Those of you that know me long enough can see where I am going with this... it means that we can develop these in managed code now :-)

I will assume that you have a scenario for actually integrating with the control panel and I will just share the mechanics. Create your managed Windows Forms application and give it whatever UI you want. You actually don’t have to do anything special in the project. In fact, you could even reuse your existing main application and just use a command line option for when it gets launched from the control panel.

So once you have the exe, how do you integrate it with the control panel? The answer is by adding some registry entries.
1. Buy yourself a GUID. In all my screenshots below, replace my guid ({ABB4AAE7-3D21-45f7-AA1C-F470FAB07B89}) for the one you have.

2. Create a key with this GUID under HKLM at the path shown in the screenshot below (hint: look at the statusbar):

3. Do the same this time under HKCR at the path shown in the screenshot below:

4. Look at the values for the screenshot above. For the first 3 values you can enter anything you like. The last value points to a path and do not worry about that right now. The 4th value (System.ControlPanel.Category) tells the system under which category you want a link to your executable to appear in. I’ve chosen 7 and 9 which are the “User Accounts” and “Ease of Access” categories. The following screenshot shows the effect of the few registry entries we created. Note how values from above match the UI (inc. tooltip).

You can find your link under both aforementioned categories and it is immediately searchable as well.

5. If you click on your item, explorer.exe will show an error box “Application not found”. Close the control panel and let’s go make one more registry entry. Create 3 subkeys as shown in the following screenshot and note how the default value under Command specifies the path to the executable (you could have specified a command line argument if you wanted):

Launch the control panel again, and this time when clicking on your link, your application will open.

Also, remember the string we entered for the System.ApplicationName registry value? If you entered the same as me, you can now launch your application from the command line
control /name Daniel.MothPanelApplet

6. An optional additional step is to specify task links under your item. This is where the path to the file we mentioned above comes in. At the moment your System.Software.TasksFileUrl value points to an invalid path. Make it point to this file after you copy it to your machine. Close Control Panel and after reopening it, under “User Accounts”, you find a something like the following:

If you navigate to the “Ease of Access” category, you’ll find a slight variation as shown in the screenshot behind this link.

More Info
There is a lot more to check out including how to change the icon that appears in the control panel, what the numbers for the other categories are, how to launch other items from the command line, design guidelines, explanations on the XML file for tasks, creating cpl items, what else is new in Vista and a lot more. The following msdn links should cover that material for you:

Tour of UI

Quick intro similar to mine

UX guidelines for control panels

Comprehensive control panel overview

TVS_EX_AUTOHSCROLL

Tue, December 19, 2006, 10:39 AM under Windows | Vista
Open your windows explorer on Vista and click around the “Folders” section in the left (below your “Favorite Links”). Do you observe two things that were not there pre-Vista? That is right, the treeview has no horizontal scrollbar at the bottom and scrolling happens for you automatically as you select nodes that are not fully visible and as you mouse over around. Resize that area to be smaller if you are not observing this effect. Now do you notice the effect? Cool :)

It turns out that you can make any TreeView behave like that, if you want to. The clue for me was accidentally coming across the TVS_EX_AUTOHSCROLL constant.

<this took me longer than what it should>
I must admit that it took me a while to get this working. First when my simple mind encountered extended style it thought: “I know those and I know how to change them for managed controls”. So I overrode CreateParams and changed the ExStyle property but that had no effect. I then assumed that the reason it wasn’t working was because I had to send it the TVM_SETAUTOSCROLLINFO message so I played with that, messing with various values since the documentation gives no clue to sensible starters and then gave up when I was still not observing the results. BTW, spy++ wasn’t helping much since prolongued use caused the machine to freeze and rebooting added to my overall frustration. Eventually a virtual slap made me realise that I need to send a custom message for the extended treeview style (not window style). Digging around I found the TVM_SETEXTENDEDSTYLE message and tried sending that. Another round of trials and errors with no luck; only after opening commctrl.h I could work out what params to send and in what order. I knew the messages were reaching the TreeView as I started using my own TreeView and overriding DefWndProc with debug statements to make sure that the message wasn't been swallowed by the managed implementation. A complete red herring came out of nowhere questioning whether I was using v6 of comctl32.dll (of course I was, my commandlinkbutton etc worked fine, but to be positive, I manifested the assembly to make sure that was indeed the case). At this point, you can imagine that I was hacking at this API for quite a while, editing code and then running the project. At some point I got lazy and my test of whether it worked or not was: Does an hscrollbar appear in the treeview. Well it turns out that, at least for the System.Windows.Forms.TreeView, the documentation is wrong: the hscrollbar does not go away with this style!! Doh! God knows how many times I had this working and thought I hadn’t because of the visual false positive :-(
</this should it what than longer me took>

Anyway, once I started testing properly again, not only it worked but I also realised that you don’t really need to send auto scroll info since it has some sensible defaults. So the bare minimum to get the TreeView to automatically scroll horizontally based on node selected and mouse position, is the following:
NativeMethods.SendMessage(treeView1.Handle, NativeMethods.TVM_SETEXTENDEDSTYLE, 0, NativeMethods.TVS_EX_AUTOHSCROLL);

If you actually want to change the speed of auto scrolling combined with a scroll timeout, then you must do this:
NativeMethods.SendMessage(treeView1.Handle, NativeMethods.TVM_SETAUTOSCROLLINFO, 30, 10); 

And if you want to get rid of the hscrollbar to make it look like the windows explorer folder view, then you must do this:
int num2 = (int)NativeMethods.GetWindowLong(treeView1.Handle, NativeMethods.GWL_STYLE);
num2 = NativeMethods.TVS_NOHSCROLL;
NativeMethods.SetWindowLong(treeView1.Handle, NativeMethods.GWL_STYLE, num2);

The pinvoke declarations for this exercise are in this NativeMethods file here.

For those of you that don’t want to repeat the above hacks for every single treeview in every single project, I’ve put all of the above in a TreeViewVista control. Just find a project that uses a TreeView already and change the ctor line to use TreeViewVista instead :-)

Launch elevated and modal too

Fri, December 15, 2006, 01:22 AM under Windows | Vista | UAC
Those of you that have attended my talks on UAC will have seen the demo where we extract a process and run it elevated (i.e. an elevation prompt requires the consent of the user). Here I want to add some extra juice to that one.

For the rest of you, basically, if you have some admin task in your application that you cannot redesign (i.e. get rid of), you still should not mandate that your whole application runs elevated (i.e. requires admin privileges). Instead, you should refactor that functionality in a separate process. When you require the use of that admin functionality from your main application, launch the other process elevated to do the work for you. There are a few ways you can launch the application elevated but the best one in this case is to manifest the application. An example of a manifest is here; change the level from asInvoker to requireAdministrator. Embed it in your project by pasting the following line in the “Post-build event command line” textbox of the project properties:
"$(DevEnvDir)..\..\Common7\Tools\Bin\mt.exe" -manifest "$(ProjectDir)$(TargetName).exe.manifest" –outputresource:"$(TargetDir)$(TargetFileName)";#1

So what is the extra juice I want to add in this post? Well there are two things that were nagging me with the way I showed how to launch the process.

One was that the UAC consent dialog that comes up was not modal to the main application (since it was being launched for another application). By default you do not observe this but since in my setup I have disabled the policy “Switch to the secure desktop when prompting for elevation”, it affects me [NOTE: I do not recommend you disable that policy, it just happens that I have it like that for historical irrelevant reasons]. I was tipped-off that to make the UAC dialog modal, you must pass to the ShellExecute call the handle of the main app.

The other thing I didn’t like was that if the process we launch elevated has its own UI, then that is also not modal to the application.

So here is the code that addresses both of the issues above:
private void LaunchElevatedProcess()
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = true; // default, but be explicit
startInfo.WorkingDirectory = Environment.CurrentDirectory; //or other if you prefer
startInfo.FileName = @"some_path_to.exe";

//// if the other process did not have a manifest
//// then force it to run elevated
//startInfo.Verb = "runas";

// Two lines below make the UAC dialog modal to this app
startInfo.ErrorDialog = true;
startInfo.ErrorDialogParentHandle = this.Handle;


try
{
Process p = Process.Start(startInfo);

// block this UI until the launched process exits
// I.e. make it modal
p.WaitForExit();

}
catch(Exception ex)
{
// user cancelled
MessageBox.Show(ex.Message, "caught it!"); //for demo purposes
return;
}
}

Enjoy :)

Managed Preview Handlers for Vista and Office

Wed, December 13, 2006, 02:25 PM under Windows | Vista
Truly fantastic article on MSDN magazine January 2007 issue: Managed Preview Handler Framework.

If you don't know what preview handlers are, on your Vista box open explorer, click on "Organise", "Layout" and then "Preview Pane". Now select a file and watch the preview pane. The file must be an office file or video or image and some others. For each file type/extension a preview handler exists that renders it in the preview pane (this also works for Outlook 2007 preview pane for attachments).

So how do you write a preview handler? Until now the answer was COM. Now with this article, Stephen Toub shares a framework that allows us to build them with managed code! Visit the article to download the framework which includes all the source code too.

Not only that, the download also includes preview handlers for files with extensions: bin;dat;csd;xps;xml;psq;isf;msi;pdf;resx;snk;zip and xaml. So even if you are not a developer caring about the framework, go get the download for the handlers themselves, to enrich your own Vista experience.

So, in a nutshell the framework has a simple inheritance hierarchy that encapsulates the COM ugliness and offers extensibility points for hooking in your own managed preview handler. When reading the article, if you are interested in the framework’s internals, keep this class diagram in mind. Another class diagram shown below should make clear how ridiculously easy it is to create these things now:

So to write a simple Hello World preview handler:
1. Create a new Class library, and reference the MsdnMagPreviewHandlers.dll from the article download.
2. Add a new code file and add to it these few lines of code.
3. Build the dll, gac it and regasm it (see the article if you have trouble with that, both tools are in your C:\Program Files\Microsoft SDKs\Windows\v6.0\Bin folder)
4. Create a new file somewhere, test.moth and watch the preview:

Now do you see how extremely cool the Managed Preview Handler Framework is? Use it for your own file formats! At a future entry I'll show you a more meaningful preview handler.

BTW, if you have no interest in preview handlers, the code is still a great example of how to wrap COM APIs so read the article for the in-depth explanation of this diagram.

WinSAT

Tue, December 12, 2006, 07:47 AM under Windows | Vista
Do you remember the Windows Experience Index (earlier known as System Performance Rating)?

Well, it is available programmatically via the Windows System Assessment Tool (i.e. the WinSAT API). This is a COM API that, at a high level, gives you back the two things: the information and a bitmap.

Here is a screenshot of the output if I query the SAT on my laptop from C# console app. Console shows the details and the pop up windows form shows the bitmap


To read the full story, download the code to run on your machine and much more detail, please visit Bart’s blog entry now.

Gadget in C#

Tue, December 5, 2006, 02:53 PM under Windows | Vista | SideShow
Goal
Walk through all the code required to write the SideShow gadget that we designed and showed screenshots of here.

Prerequisites
1. SideShow
2. Gadget Fundamentals
3. Designing with SCF
4. Microsoft.SideShow.dll

Installation/registration revisited
When talking about the basics of SideShow gadgets you saw how we need to create the appropriate registry keys and run a command for the Gadget manager to notify the user. You can actually achieve all of those actions in managed code and specifically with one line of code (I’ve separated the parameters into their own variable to make the line of code self-explanatory):
bool registerForAllUsers = false;
Guid gadgetId = new Guid("{65EA3E9A-8F83-4139-8139-94DE7E4149B0}");
string startCmd = String.Empty;
string iconPathNameAndResourceId;
bool onlineOnly = false;
Guid? propertyPage = null;

GadgetRegistration.Register(registerForAllUsers,
gadgetId, ScfSideShowGadget.ScfEndpointId, "The Moth", startCmd,
iconPathNameAndResourceId, onlineOnly, GadgetCachePolicies.KeepOldest, propertyPage);
To uninstall/unregister the gadget we need another line of code
GadgetRegistration.Unregister(registerForAllUsers, gadgetId);

ScfSideShowGadget class
Writing a gadget in managed code begins by creating a ScfSideShowGadget object (that you must remember to Dispose when your gadget exits). The way the gadget is associated with the registration/installation metadata is via the use of the same gadget GUID, of course. The following code snippet demonstrates that:
  ScfSideShowGadget gadget = new ScfSideShowGadget(new Guid("{65EA3E9A-8F83-4139-8139-94DE7E4149B0}"));
// send content to device
Sending glance data
Sending glance data is simply one line of code:
gadget.AddGlanceContent("some short summary \r\n" + DateTime.Now.ToLongTimeString() + "\r\n http://www.danielmoth.com/Blog \r\n Even more text all the way to the \r\n bottom");

Sending Images
Any images rendered on the SideShow-compatible device must be sent there of course and their content ids can then be referenced from the SCF XML snippets. The following code shows sending of the images:
string path = @"C:\Users\Public\Pictures\SideShow\";
string b = path + "SSForest.jpg";
string d = path + "SSgarden.jpg";
string m = path + "SSmenu.jpg";
string r = path + "SSdive.jpg";
gadget.AddContent(MothImages.Background, ImageContentTransforms.None, new Bitmap(b));
gadget.AddContent(MothImages.DialogIcon, ImageContentTransforms.KeepAspectRatio ImageContentTransforms.StretchToFit, new Bitmap(d));
gadget.AddContent(MothImages.MenuIcon, ImageContentTransforms.ReduceColorDepth, new Bitmap(m));
gadget.AddContent(MothImages.RandomImage, ImageContentTransforms.None, new Bitmap(r));
In the code above, MothImages is a simple class for holding the integer image content ids (as opposed to hard coding them in the body of the code).

Sending SCF content
As you’ll recall from the introduction to SCF, each page is its own SCF body tag. When sending pages to the device, we make a single method call per page that we want to send: a different overload of the AddContent method we already saw above for sending images. The code that follows is what was used to create *all* the screenshots of my previous SideShow blog post:
gadget.AddContent(MainMenuPage); //MainMenuPage is a property that returns a string
gadget.AddContent(ContextMenuPage); // ContextMenuPage is a property that returns a string
gadget.AddContent(ContentPageA); // ContentPageA is a property that returns a string
gadget.AddContent(ContentPageB); // ContentPageB is a property that returns a string
gadget.AddContent(ContentPageC); // ContentPageC is a property that returns a string
gadget.AddContent(DialogPage); // DialogPage is a property that returns a string
The above piece of code assumes that the properties we pass into the AddContent method calls return the XML as we designed it last time. This could look something like this:
public static string MainMenuPage
{
get
{
string content;
content = File.ReadAllText("page1.xml");
return content;
}
}
In the code above, page1.xml would hold the XML of this SideShow screenshot.

SCF creation revisited
So the above few lines of C# code register our gadget, create it and send both glance data and content data! The only thing it assumes is that we have created the SCF XML in a file already (i.e. in page1.xml).

However, Microsoft.SideShow.dll offers a class (Scf) with static methods (Body, Br, Btn, Clr, Content, Dialog, Div, Em, Img, Item, Menu, Txt) each with appropriate overloads that accept as parameters the attributes you would set on an SCF XML element and returns the equivalent XML. So, if you don’t want to hand craft the XML, you can get some intellisense help doing so programmatically (still no graphical way though).
For example, recall the screenshot of this XML and page? Here is the code that can generate that:
    content =
Scf.Body(
Scf.Menu(MothPages.MainMenu, "Main Menu Moth", ScfSelectAction.Target,
Scf.Item(MothPages.SomeText, "Points to 1st content page"), // 1st overload
Scf.Item(MothImages.MenuIcon, null, MothPages.WithImage, "Click for 2d one"), //2nd overload
Scf.Item(null, MothPages.ContextMenu, MothPages.MixedText, "This adds to the context menu"), // 2nd overload with context menu
Scf.Div(),
Scf.Item(MothMenuIds.Open, MothImages.MenuIcon, null, MothPages.DialogExample, "Shows dialog"), //3rd overload
Scf.Item(null, MothImages.MenuIcon, true, true, null, MothPages.MixedText, "IsDefault and points to 3rd content page"), // 4th overload
Scf.Item(null, MothImages.MenuIcon, false, false, null, MothPages.DialogExample, "I am !enabled"), // 4th overload, default & enabled
Scf.Btn(DeviceButton.Right, "Won't show up", MothPages.ContextMenu)
)
);
In the code above, any class starting with Moth is a simple class for holding the integer content ids. As a further example, the following screenshot shows some SCF XML and the c# code required to generate it (for the two pages that look like this and like that):

What’s left
Tons of stuff :-D
There are many more developer capabilities that we haven’t talked about on the SideShow platform and, instead of introducing them generically, I’ll introduce them as part of the managed API over subsequent posts... or maybe I should wait until we make Microsoft.SideShow.dll publicly available before doing so... let me know if you’d like to learn about it beforehand regardless...

Designing SideShow gadgets with SCF

Thu, November 30, 2006, 02:35 PM under Windows | Vista | SideShow
Please read the intro to SideShow and the SideShow gadget fundamentals posts as they provide essential background to this post.

Glance data
Your gadget may send to the SideShow device a complex UI and various navigation structures between pages of your UI. Regardless of whether it does that, it must first send what we call glance data. This is just plain text, and it is the text that appears next to your gadget icon when the user browses the gadgets on the device. Examples of glance data for the Windows Media Player, Picture Viewer, Windows Mail and our gadget, you can see in the following screenshot:


Simple Content Format (SCF)
Simple Content Format (SCF) is a simple XML format. It is used to describe pages and the elements on a page (except of course the very first glance data page which we established is plain text) including how everything maps to the buttons on the device. For an overview of SCF, click here.

When we look at the API later, we'll see that we send XML fragments to the device and each XML fragment represents a page.

Pages
A page is what is displayed on the SideShow device. For Windows Forms developers, think of this as the equivalent to a Form, except there is no designer and the way we describe what the page contains is via the SCF (which as I said is just XML, in this case an XML element that can contain other XML elements). All pages have a unique content id. Page types can be: content, menu, dialog.

For more, see SDK for body, content, menu and dialog.

Page Items
Elements on a page are the things that end users see on a page on the display (and the things that sometimes the hardware button actions apply to). For Windows Forms developers, think of this as the equivalent to WinForms Controls, except we don't drag and drop them on the page and the way we add them is via the SCF (they are just XML elements). Each element must have a unique content id. There can only be one element per (imaginary) row on the display, a bit like the guidelines for Smartphone development. These elements can be: menu item, button, image, text and blank lines.

For more, see SDK for item (including div), btn, img, txt (including clr and em), br.

Buttons
SCF-compatible SideShow devices must have at least 5 physical buttons: UP, DOWN, ENTER, BACK and MENU.
- UP and DOWN have a fixed function of navigating up and down a menu page (or a context menu) and scrolling up and down a page that shows a vertical scrollbar.
- MENU shows a fixed built-in context menu [Back, Home] but you can also add your own menu items above the 2 built-in ones.
- BACK returns to the previous page. The BACK button can also be overridden if you desire to do something specific to your page.
- ENTER (aka SELECT aka OK) takes whatever action you have assigned to a menu item. The ENTER button can also be overridden if you desire to do something specific to your page. Also, the ENTER button is what navigates from the glance data page to your first real (SCF) page.

The other two buttons that may be present on an SCF device are LEFT and RIGHT. If they are present, you can also assign to them custom actions relevant to your page (but also provide those on the context menu of the page in case they are missing).

Just FYI, for non-SCF devices you can also have buttons for PLAY, PAUSE, STOP, REW, FF.

Images
Note that in addition to the glance data and in addition to XML representing each page, we can also send images (with their own content id of course) that can be referenced from pages and elements.

Mapping SCF to screenshots
If you followed the links to the SDK that I provided previously, you can read all about what SCF element combinations are allowed, what attributes each element accepts for configuring its appearance/behaviour etc. Let's see how easy the SCF is by mapping the XML to the screens they result in.

1. In the screenshot below you can see a menu page with 6 menu items and a divider line after the 3rd menu item. The content id of this page is 1.

Notice how the XML elements map to the screen elements?
- Most menu items have their imgid set to a content id that represents an image that we have also sent to the device (along with the XML) - the 1st and 3rd menu items do not have this attribute and hence there is no icon next to the text for them.
- Looking at the XML you can tell that the 5th menu item is the default one that would be preselected when this page was loaded.
- The last menu item is disabled (its appearance doesn't show that, but if you hit ENTER after selecting it, nothing happens!).
- The 3rd menu item has an attribute that the others don't: menuid. This means that if we press the MENU button after selecting this menu item, the context menu will include menu items that we specified on another page with a content id of 6. If we press the MENU button on any other menu item, just the default built-in context menu will appear.
- Pressing the UP and DOWN buttons navigates up and down the menu structure.
- Pressing the ENTER button will navigate to the page that has a content id equal to the target of the menu item (see the XML in the screenshot).
- Finally, notice how there is a btn element in the XML. This does not show on the content page, but if we hit the RIGHT button it will navigate to whatever has a content id of 6 e.g. another page.

2. In the screenshot below you can see a content page with 3 text elements and an image element after the 2nd text element. The content id of this page is 2 (so this will appear when on the previous menu page we select the 1st menu item and we hit ENTER).

Notice in the XML how the text attributes align and rgb control the alignment and colour of the text. Notice how the image element references an image with id 21 that we must have also sent down to the device.

3. In the screenshot below you can see another content page with just one text element. The content id of this page is 3.

- This shows wrapping in action for the text element (wrap="1"). If that was not set then the text would have been chopped off. In the XML we also see a button element.
- This is not shown on the screen but if we hit the ENTER button then we would navigate away from this page and on to the page with a content id of 4. If this button element was not in the XML, then hitting the ENTER button would not do anything.
- Observe how the content element also specified the bg attribute pointing to content id 31. Clearly content id 31 must be another image that we sent to the device and it is now set as a background to this page.
- Also notice the menuid attribute of this content page: 6. So we must have defined a menu page with a content id of 6 that will be merged with the default context menu when we press the MENU button.

4. In the screenshot below you can see the final content page of this gadget, with two text elements separated by two blank lines. The content id of this page is 4.

This page demonstrates that text elements can have two other nested elements that allow the same line of text to have mixed colouring and emphasis.

5. In the screenshot below you can see our first (and only) dialog page with two text elements and 3 buttons. The content id of this page is 5.

What we see here is that for dialog pages, the buttons can appear on the screen (except if the button element is assigned to the BACK button). Also, the dialog element has an attribute for an image that it will insert before any other element (something like a banner).

6. In the screenshot below you see a menu page with a single menu item. The content id of this page is 6.

Do you recall above, that content page with id of 3 had specified as its menuid the content id 6? If you press the MENU button on that page, it is the screenshot above that will appear. Our menu item is merged with the default context menu. Note that if you hit the RIGHT button on the first menu page we described, then a full screen menu page will appear with just the single menu item we define here.

Tool support
I encourage you to study the built-in gadgets with the knowledge you gained above and mentally map the elements you see on the screen to the SCF elements. Note that the two games in the simulator are not gadgets (hence they don’t appear in the control panel), instead they are built-in NETMF applications.

There is no tool for designing the UI of the content that your gadget will send down to the device. This is a great opportunity for some smart individual to create one! How hard would it be to have a GUI designer tool that spits out valid SCF? ;-)

Regardless of how the SCF gets created, each page (i.e. each complete body element) has to be sent down to the device. Once sent, you can update it from your gadget periodically or when your data on the PC has changed. As an example, the Media Player gadget sends every 1 second a page with the same content id to the device. The only thing that changes on that page is the progress duration of the song. So how do we send SCF to a SideShow-compatible display?

Native API
There is a native COM API for those still living in that world :-)

If you do want to mess with the ISideShowSession, ISideShowContentManager, ISideShowContent and their friends then here is my top tip: There are 4 different sample SideShow gadgets in the SDK. They all use the COM API so you can explore them. In fact, the Picture Viewer gadget I linked to earlier is pretty much the same as the one in the SDK.

Managed API
That will be shown next time - honest!

SideShow gadget fundamentals

Wed, November 29, 2006, 08:14 AM under Windows | Vista | SideShow
In a previous post I described the new Windows Vista feature: SideShow. Please read that as I will assume that you have done so since it helps if you perceive the terminology and concepts in the same way that I do :-)

Gadget and SideShow device interaction
Remember that gadgets are just applications running on your laptop/PC that send data to a SideShow-compatible device. The gadget does not run on your actual auxiliary display. If you ever read "browse different gadgets on your SideShow display" you can interpret that as "browse the contents that the various gadgets from your laptop send to your SideShow display".

At a high level think of the gadget communications being one of the following (I cover these later):
- Gadget sends a message with content to the device.
- Device may optionally send event back to the gadget (e.g. at a click of a hardware button).
- Gadget may optionally send a notification to the device.

SideShow target
Before you write a SideShow gadget it helps if you have a target to test it on. If you have a real device great, otherwise your best friend is the SideShow simulator, which comes with the Windows SDK. Different SideShow devices will have different capabilities. At the most basic think about a 2-line monochrome text display with no hardware buttons. For this device you can only update it with text. At the other end of the spectrum, devices may understand the iCalendar format so you can send calendar data to it (e.g. the simulator and any full NETMF implementation) and it will interpret it in a rich manner. You can even plug custom content formats for your own SideShow-compatible device. Having said that, most devices will understand the Simple Content Format (SCF) , a device-independent XML format which is core to SideShow (I cover this later). There are APIs for querying at runtime the capabilities of the SideShow target(s) that the user has connected. In everything I write/do, I am going to assume that the target supports the SCF (e.g. the simulator does).

Gadget installation
Usually installation is left as the last thing you learn in any application development, but in this case it is important to understand this first as you will have to install the gadget even on your own dev machine before you do anything (and by "anything" I mean run it, debug it etc).

Gadget installation is simply a collection of registry entries in the right place (think of these as 'gadget metadata'). For example, for the built-in gadgets you can browse their registry entries by navigating to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\SideShow\Gadgets. Under there you will find keys that are basically GUIDs. Every gadget has its own application GUID that the developer must generate (I buy mine from uuidgen or guidgen). Under each GUID, there are various values that describe the gadget. The following screenshot shows the registry entries for one of the Outlook 2007 gadgets:

This one shows the Picture Viewer gadget (available from the online gallery):

I also have registry screenshots of the 2 built-in gadgets if you are away from your Vista box right now: Windows Media Player and Windows Mail.

When you deploy your gadget to other computers, you'll have a setup program of some sort to do this for you but for now let's add the registry entries for our gadget manually. Of course, we will install it for the current user only, here: HKEY_CURRENT_USER\Software\Microsoft\SideShow\Gadgets (i.e. same path as above but instead of HKLM we go to HKCU).

First create a key under the Gadgets key with your own guid for your gadget (TIP: at the end of all this, if you want to remove the gadget simply delete this key!).

Under that key, we need to specify the following:
1. Endpoints that we support. I will only support the SCF endpoint: {A9A5353F-2D4B-47ce-93EE-759F3A7DDA4F}
2. FriendlyName. Mine will be "The Moth"
3. OnlineOnly (i.e. content is not cached on device, and computer must be on). Mine will be only online: 1
4. Icon. Nothing for me, so it will get the default.
This is what your registry should look like after doing the above:

If you were doing all of the above in an installation program, you should also run at the command line the following to invoke the Gadget Manager for a better user experience:
Schtasks.exe /run /tn Microsoft\Windows\SideShow\GadgetManager

Try it manually! You’ll see the following screenshot:

If you click on that notification (which is what your users would have seen) it will take you straight to the SideShow control panel. To be honest, you can go straight to control panel after you made the registry modifications and refresh. Your control panel should now look something like the following screenshot:

(my additional device column is irrelevant for now, I’ll talk about that later).

Hopefully you are running your simulator. Check the box next to the gadget under your simulator and notice how the gadget is available to use. See following screenshot of what it should look like on the simulator:


What is left?
So now all we need is a windows process for our gadget. That is easily found: Either create a brand new GUI exe or a console EXE or a blind exe or use an existing exe.

Once we have an EXE, then all we need is to write some code in there that calls the relevant APIs to send content down to the device. Before we do that though let’s think what that content should depict. In other words, what should the UI of our application look like?

NOTE: Where it now says "(No information availalbe)", we should have our first text content. When the user clicks on OK, we should show a full page of more content etc.

This blog post is getting long already so in my next SideShow blog entry we'll design in SCF a few pages with elements, and also see how to send that down to the device using the SideShow API.

Windows SDK

Tue, November 28, 2006, 11:49 PM under Windows | Vista
I say this at every given opportunity (on the blog, in my talks etc) but it is so important I thought I'd dedicate a permalink to it.

If you are a developer and have installed Vista, the first thing you should download is the Windows SDK. It is in there that you can find goodies such as Vista Bridge or the SideShow simulator. There is also plethora of native samples for the 7000 new native APIs in Windows Vista. In addition, you'll find tons of managed samples for .NET v2.0 and .NET Framework v3.0. This makes sense since the Windows SDK is the unification of what was known as the platform SDK and the dotnet SDK. Download it now!

UAC: Get your links here!

Mon, November 27, 2006, 06:05 AM under Windows | Vista | UAC
Unsurprisingly, after my UAC talk this morning (that I mentioned here), there was a lot of interest and I promised to publish helpful UAC links (in addition to previous mentions on this blog here, here and here). True to my promise, find them below!

1. Understanding the feature before jumping to questions is important. Don't take anything I say as gospel (always a dangerous tactic!) and instead read the official word:

- Short what is it by security MVP on technet.

- UAC for developers (written during Beta 1 but still valid)... and an updated one here.

- UAC for IT Professionals (surprisingly even though I am a developer, I found it quite interesting).

- UAC 91 page document for developers is available for download (a must read).

- The COM Elevation Moniker (all you want to know and more)

2. Now that you understand the feature, start testing your applications as standard user on Windows XP. If it works there, from a UAC point of view, it will work on Vista.

- Standard User Analyzer tool... requires the Application Verifier.

- Get the Application Compatibility Toolkit (ACT) 5.0

3. A lot of the compatibility issues are relevant to installations.

- UAC in MSI blog.

- MSI Patching Technology (tip: explore the other links from the tree on the left).

4. Related topics that I received questions on and promised I'd provide links to
- IE7 Protected Mode on Vista.
- Service changes in Vista.

5. Still got questions? Get them answered using the resources below:
- Even though it is now closed, there is good content on the UAC blog.

- Still active and open to questions is the Vista Security blog.

- When all else fails, first check the msdn forums where you can post any question you like:
* MSDN forum, security for applications.
* MSDN forum, app compat on Vista.

6. For your non-technical, non-developer friend:
For a non-technical plain English version of the UAC story (as plain English as the topic can get) this isn't bad and it also is not an official Microsoft explanation but it makes good reading!

I provided other generic Vista links a while back, and Karl just dropped me a line telling me about their community site that looks interesting: AeroXperience.

Vista: SideShow

Mon, November 20, 2006, 09:14 AM under Windows | Vista | SideShow
I've very briefly mentioned SideShow recently here. My first intro was at MEDC and you can watch that session (APP322) for free (note that Viji is no longer with the team).

"Side what?"
SideShow is a new Windows Vista platform. It enables a variety of auxiliary display devices to be connected to Vista so they can display information from applications running on Vista. In some cases from the display you may control applications running on Windows.

For the information to be exchanged between the display and Windows, developers must write a SideShow gadget (note that this actually runs on the OS, not the display!). The gadget can gather the data from anywhere it wishes and then using the SideShow APIs can send it to the display (more on this later).

"What display(s)?"
So what display are we talking about here? The example that has become synonymous with SideShow (to the extent where most people miss the point and think it is the only SideShow implementation!) is the in-lid attached laptop display. This implements SideShow fully, is connected to Windows via USB (even though it is embedded in the display) and the driver for it ships with Vista. For those that are curious, it is actually running the .NET MicroFramework.

Other display examples would be a phone, a remote control with built-in screen, a keyboard with built-in screen, wearable display devices, music players, digital picture frames, insert your own hardware/display here etc. Photos of examples of these you can see in various articles by searching the web. Remember, these can be connected to Vista with any protocol they want (e.g. bluetooth, IR, proprietary etc).

"Why?"
So, previously, to connect a display to Windows you would have to choose a transport, implement the display-side of things, implement some custom protocol for exchanging data between OS and display, and then finally, implement a custom Windows-side application/driver for gathering and sending the data. SideShow, standardises all of this. In particular, as developers, you just need to learn the SideShow API and call it from your gadget and then whatever other hardware becomes available that supports the SideShow infrastructure will automatically work with your gadget!

It’s a bit like those dual display phones. You don't have to flip the phone open to see what you want; you can just glance at the smaller outer display and get the information you quickly need. Your imagination is the only limit to writing great on-line gadgets. SideShow devices can also work when your computer is off (using cached data)! You can even schedule Windows to wake up periodically so the cached data gets refreshed if that is applicable in your scenario. You could control a powerpoint presentation from your mobile phone (and that can be any phone not just Windows Mobile, as long as there is a SideShow driver for it). You could have small displays on the PC towers in a server room, glance at data on the box there rather than having to remote connect. For other ideas, again just search.

Personally, I can see a lot of killer ideas manifesting themselves on the SideShow platform once more devices become widely available. Be one of the first to get there by extending what your application can do, with a companion SideShow gadget.

"Not quite sure I get it, tell me more"
- A short blurb for SideShow from a consumer perspective can be seen here.
- If you have the time, watch this channel9 video (featuring Dan Polivy) that explains all of the above much better.
- Subscribe to the SideShow blog for more info as it becomes available.

"OK, I am hooked. How do I write gadgets?"
First, you can browse the gadgets and SideShow devices you already have on your Vista machine. Simply go to the "Control Panel", select "Hardware and Sound" and then "Windows SideShow": it should look something like this. Then install the simulator which will make your panel looks something like this.

You can very easily write gadgets (essentially just an exe on your Vista machine). Remember, they are separated from the communication protocol and from the actual target display so you only have to do two things:
1. "Design" your screens (they will be represented in XML)
2. From your gadget, call the API that sends the XML to the device

All you need to know is in the SideShow SDK. Soon I'll show you how to build a simple gadget in C#. Stay tuned :-)

Changes in Vista RTM

Thu, November 16, 2006, 02:55 PM under Windows | Vista
I’ve only been running the latest RTM version of Windows Version 6.0 (Build 6000) for 4 days and I’ve been trying hard to find new stuff that wasn’t there in RC1 so I could blog about it... Unfortunately, I am not having much luck... all my demos work fine and I can find no new features (unless you count increased speed and stability as features). Of course, I was expecting that, but I was hopeful there would be something new...

So when you install Vista (it is available right now on the msdn subscriptions page) expect almost no new features. I say "almost" because there are a few new desktop backgrounds to choose from, a whole bunch of new icons used for various built-in apps (e.g. mail, sidebar) and a complete new set of sounds (I like them, very subtle... very zen-like) :-)

Also, FYI, I went for an upgrade from RC1 and it worked fine (same is not true for RC2, which is why I did not install that on my main machine ;-)). The only thing the upgrade lost was my Quick Launch icons/apps and some other setting (which embarrassingly I don’t remember now!).

BTW, I also removed Office 2007 B2TR and installed the RTM (you cannot just upgrade that). Absolutely no issues there except I also had to remove some other apps that made the installer think office b2tr was still installed.

Vista-only features for the managed developer

Mon, November 13, 2006, 08:10 AM under Windows | Vista
UPDATED on 23 June 2007 with some Plus links and new items 13-15.

Following my Vista session at Tech Ed, I was asked to create a blog entry that indexes all my other blog entries that provide supporting material for the topics I covered. I thought I'd also include topics from my UK version of the talk, which is longer. Enjoy!

1. Glass
Follow this link, to find at the end of the first paragraph a bunch of links to my other blog entries.

2. Task Dialog, CommandLink, CommonFileDialog, cue banner plus Vista TreeView and ProgressBar
Follow this link, for my screencast and 5 links to my blog entries plus this and that.

3. Power aware
Follow this link, for my demo code and a few supporting links.

4. Windows Error Reporting & winqual
Follow this link, for my screencast and for 5 links back to my blog entries.

5. Restart & Recovery APIs
Follow this link, for my screencast and for 3 links back to my blog entries.

6. Restart Manager
Follow this link, for my screencast and a link back to my blog entry.

7. Sidebar Gadgets
Follow this link, for my screencast and 3 links back to my blog entries.

8. User Account Control
Follow this link, for a link to another blog and 2 links to my other blog entries (one of which contains a link to a screencast), plus my UAC category.

9. RSS API
Follow this link, for some tips on using the RSS platform including 2 links to my other blog entries. NOTE: RSS API is also available on Windows XP if you have installed IE7.

10. Search
Follow this link, for my demo code and links to other relevant useful info.

11. Non-dev
In addition to the Visual Studio demos above, I also demo the new shell enhancements by going through some of the new aesthetic and usability improvements. Finally, I touch upon the new aero guidelines and also the SKUs.

12. Slides
You can download my powerpoints from the UK msdn page [part 1 & part 2], as presented in October 2006. Plus my slides from the UK Vista launch.

If the links above are not enough, here is a collection of Vista developer links I captured back in May (so I can't promise anything about their relevance now that Vista RTMd).

13. SideShow
Watch the video and follow the links form here, and read bottom-up my SideShow category.

14. Preview Handlers
Watch the video and follow links form here, and also see this.

15. Etc
A couple smaller things that are Vista-only accessible from managed code are WinSAT and Control Panel Items.

VB6 does glass on Vista

Sat, October 14, 2006, 07:00 PM under Windows | Vista
The other day at one my talks somebody asked me if the new Vista native APIs I show callable from managed code are also callable from VB6. I hadn't thought about that before, but in principle, yes, they should be. He was specifically interested in glass (glass, as in what I talked about here, here, here, here, here and here.).

Unsurprisingly, it took me longer to download the VB6 iso, to install it on my laptop and to remember how to work with that IDE, than what it did to get glass in VB6. A form, a module and a total of 11 lines of code later and the following screenshot shows the project running (or if you prefer without transparency):


Note that just like with Windows Forms (but unlike WPF), actually making controls look good on the glass surface is not trivial (unless you enjoy painting everything yourself!). You get a glimpse of the challenge here and a full blown project here.

Vista: Restart Manager

Sat, October 14, 2006, 03:45 AM under Windows | Vista
Intro
It is amazing how as end users we all take for granted that before we install something we need to save our application state, manually close everything, install the new thing, manually restart every app we were using (if we remember what they were) and try to get to the state we were before! How many times have you installed an application (or completed a Windows Update or some other patch) and then had to restart your machine? How irritating is that?

Restart Manager promises to make that experience a thing of the past. Personally, I'd like to live with Vista for a bit longer before I subscribe to that promise but I have to admit initial experiences are promising!

So what does Restart Manager (RM) do?

Fundamentally, when a RM-aware piece of software installs, it will ask all RM-aware applications to shutdown, assuming the said applications are holding resources (e.g. files) that it needs to update. The RM-aware app, will listen to the request and shutdown, saving its state! When the installation has completed, it will then restart all the RM-aware applications. The RM-aware application will then restore its state and the user has a nice experience. The classic example is that you have left Word open with a document you are working on and gone home. Overnight a patch is available and windows update does its job. So it closes down Word, install whatever, then restarts Word so when you arrive in the morning, you can't even tell what happened because Word is waiting for you where you left it with the document you were last working on :)

If the update involves a critical system component so a windows reboot is unavoidable, a reboot will take place but after reboot the RM-aware applications will also restart!

Now that Vista offers this technology, reaching this seemingly imaginary world is down to us, application developers. And since you are reading this blog... managed developers! So what is it we need to do?

Developer actions
Well, reading the above should have given you a clue :)
1. We need to make our installations follow the RM philosophy and
2. we need to make our applications at runtime also play ball

To achieve the first action we can simply use (directly or indirectly via commercial package) Windows Installer v4 and you are pretty much done!! If you have chosen an alternative deployment technology then ditch it and switch! No I am only joking, if you do wish to use something else, then you must manually work with the API which resides in rstrtmgr.dll. A typical series of calls is to create a session (RmStartSession), then register the resources we created (RmRegisterResources), then shutdown the resources/processes (RmShutdown), later on restart them (RmRestart) and finally end the session (RmEndSession). I may post a full C# sample in a future blog entry.

To achieve the second developer action for your application, you need to do a further two things:
a) Register with the system for restart, and be capable of restoring your state when (re)starting up
b) Listen for the message from an installation program that you are about to shutdown (good opportunity to save state etc)

The first of these actions is identical to what we talked about before for unexpected crashes/hangs. Now you see that there is a dual benefit to calling RegisterApplicationRestart as I’ve already mentioned in this article.

The difference with that scenario is that in this case your application doesn't crash, instead it is being asked nicely to shutdown. To listen to that request you need to hook into your window's message loop and listen for a specific message as per the example below:
    protected override void WndProc(ref Message m)
{
base.WndProc(ref m);

if (m.Msg == WM_QUERYENDSESSION) //0x0011
{
if ((m.LParam.ToInt32() & ENDSESSION_CLOSEAPP) == ENDSESSION_CLOSEAPP) //0x1
{
// some installation will shut us down next, so do some cleanup (prepare for it)
File.WriteAllText(Environment.CurrentDirectory + @"\rm.txt", "for demo purposes");
//MessageBox.Show("intercepted", “RM request”);
}
}
}
Other links
If you want to find out more about Windows Installer 4.0 working with Restart Manager then there is this video on channel9 (watch the first 3’ and then watch another 4’ starting at 15’).

There is public/external mention of Restart Manager over at eWeek.

For the developer types, lookout for a nugget coming real soon!

Vista: Sample Sidebar Gadget

Thu, October 12, 2006, 09:33 AM under Windows | Vista
While most people think they know all there is to know about Sidebar and Sidebar gadgets, I strongly recommend you read my blog entry that details the feature: Sidebar Gadgets. The best way of course is to actually try out all the system gadgets that give you a glimpse of what is possible. Only then you'll have acquired an appetite to go build your own!

First step to creating our own gadget is to know what a gadget looks like on the file system. Easy one that... it is just a folder! A folder with a .gadget extension placed in one of two places: the system folder or the user folder (more on both follows).

1. Navigate to the following path on your machine (copy it and paste it on your explorer window): "%userprofile%\appdata\local\microsoft\windows sidebar\gadgets".
2. Create a folder named "moth.gadget".
3. In that folder, place this gadget.xml file.
4. Drop in the same folder this daniel.html file (right click and save it, don't worry about what is inside it for now).

Go to the gadget picker and you see your gadget (“Moth Gadget”)! So all we have to do to get our gadget in the gadget picker is use a manifest which is always named gadget.xml. Now go ahead and open the XML file in your favourite editor (~20 lines) and check out the element names. It should be obvious what each one describes (name, version, author, description, icon etc) and also obvious what you need to change for your own gadgets. Spot the correlation of values between the XML file and the text that appears in the gadget picker. Looking at the gadget.xml contents, notice under the base element (under the host element, under the hosts element) the attribute "src"? That points to where the actual content of your gadget is in terms of how it renders itself when added to the Sidebar (and that is why we added the html file).

5. Drop in the same folder an image with a name of “daniel.PNG” (I have one here if you are desperate for images). Now in the gadget picker we can also see our own icon for the gadget (rather than the default).

6. Now add the gadget to your Sidebar. If everything went to plan, you can see on a plain white background some text. This text is the machine name of the computer you are running on.

Open the html file in your favourite editor and observe its contents (~25 lines). It has 3 sections: script (the guts of all Sidebar gadgets is script), head (for styling) and body (for context). It should be fairly obvious to web developers what it does: In the script section we setup the 'machName' span to the return value of a gadget API (System.Environment.machineName). In the body we simply render the machName. "Not running in Sidebar!" is what you see if you open the html file outside of Sidebar of course.

So to summarise, gadgets are basically DHTML. A combination of html+script+css+images and you've got it (preferably PNG files so you can play with some transparency). Of course, you should also take advantage of the Sidebar gadget API to create powerful gadgets.

Questions that usually pop up at this stage:
Q1. (tone of disbelief) How powerful can I possibly make a gadget when I am only using DHTML?
A1. Very :) Just check out the gadgets that ship out of the box. You can view all of that code for inspiration by browsing to "C:\Program Files\Windows Sidebar\Gadgets" <-- this is also my top tip :)

Q2. Where can I find more about the Gadget API?
A2. On msdn of course. The gadget API page appears empty, but you can navigate to the topics below it from the treeview on the left.

Q3. Is there a tutorial more comprehensive that what you just showed?
A3. My sample above demonstrates how easy it is with essentially two files to hook into the gadget plumbing. The best samples are the ones on your Vista machine as per Q1 above. However, you can find two additional more comprehensive walkthroughs: One on msdn and one on technet. Enjoy!

Q4. No offense to web people and script fans, but can I not write these in binary code?
A4. Of course you can use ActiveX. You may lose the simplicity of deployments but you gain all the richness of ActiveX technology. Follow the link for more on gadgets with activex.

Q5. How about .NET code and in particular WPF?
A5. While originally this was the plan, regrettably the feature had to be cut (and will hopefully re-appear in a future version). There are a few samples of using WPF with gadgets but they are more a proof of concept rather than an attractive (or a supported) scenario. One such example (via an XBAP) is here.

Q6. Any other gadget resources?
A6. If you consume the links above (and from my previous post on Sidebar), as a side effect you'll discover other resources :) There is an example of using Atlas to call web services (very popular scenario) from gadgets here.

My nugget on the subject should be out next week

Vista: Sidebar gadgets

Wed, October 11, 2006, 11:20 PM under Windows | Vista
After talking about gadgets in general, let's focus on Sidebar gadgets specifically.

Sidebar gadgets are hosted, managed, installed, picked in Sidebar. Sidebar without gadgets is useless and gadgets without Sidebar are non-existent. Sidebar contains gadgets (gadgets can also be dragged onto the desktop area). Multiple instances of the same gadget can appear on the Sidebar.

Sidebar is a Vista feature and it is basically a pane on the side of the screen (whichever side you want on whatever monitor you want). It is an executable (sidebar.exe) and also has a systray icon. You can "close" the Sidebar in which case it is still running and is minimized to the systray or you can "Exit" the Sidebar in which case it is gone for real (along with any gadgets you dragged onto the desktop).

Sidebar can be configured to be always on top (or not) and the same is true of any gadgets that were dragged onto the desktop area. All gadgets have a thumb for moving them around and a close button for removing them from the Sidebar. Some of them also have a config button (little spanner icon). Furthermore, those gadgets can have their opacity tuned. Right click on the gadget and you get this menu:


Clicking on the Sidebar systray icon will bring to the front the Sidebar (if that was behind a window) and also any gadgets on the desktop (if they were behind a window). Right clicking on the icon will show a menu and right clicking on the Sidebar itself will also produce a menu. Both of these menus are in the following screenshot:



Clicking on "Properties" produces the following dialog.


The last thing to know about Sidebar is that there is a gadget picker that previously looked like this and now looks as follows (access it from the top of the Sidebar "+"):


You can add a gadget to the Sidebar from the gadget picker by double clicking, right clicking and selecting "Add" or finally by simply dragging and dropping. To remove the gadget from your system, right click on it in the gadget picker and select "Uninstall".

As the screenshot above shows there are 11 gadgets shipping out of the box.
- Calendar (Browse the days of the calendar)
- Clock (Watch the clock in your own time zone or any city in the world)
- Contacts (See a list of Windows contacts, search for a contact, or select a contact to see e-mail address and phone numbers)
- CPU meter (See the current CPU and RAM)
- Currency (Convert from one currency to another)
- Feed Headlines (Track the latest news, sports, and entertainment headlines)
- Notes (Capture ideas, notes, and reminders in a quick and easy way)
- Picture Puzzle (Move the pieces of the puzzle and try to put them in order)
- Slide Show (Show a continuous slide show of your pictures)
- Stocks (Monitor your favourite stocks)
- Weather (See what the weather looks like around the world)

These are the system gadgets and the user can install additional gadgets. I encourage you to familiarise yourself with these OOB gadgets as collectively they show some of the cool thing gadgets can do.

Before we close the description of this feature, it is important to understand that the security aspects have been thoroughly thought of and you can read about some of them here.

Next we look at the developer story with a sample Sidebar gadget :-)

Gadgets, gadgets, gadgets

Wed, October 11, 2006, 03:54 PM under Windows | Vista
If you didn't know about it, then yes it is true. Our marketeers have managed to name 3 slightly different things with the same name. I can sort of see where they are coming from, since in all 3 cases we are talking about task specifics mini-applets that are not quite full blown applications but are also not web pages so “gadgets” seemed appropriate for each category.

I am talking of course about (note the spelling/casing!)
* live gadgets (web)
* SideShow gadgets (Vista)
* Sidebar gadgets (Vista)

The compatibility between these is not there *yet*. Each has its own API that the other two hosts will not understand. SideShow gadgets are probably more removed from the other two. Live gadgets can be made under certain circumstances to run in Sidebar (via an iframe) but the vice versa story is not as good. I am being vague on the compatibility as I know it will get better in the future and the current story is ever changing. But here I am talking about (in)compatibility when I haven’t introduced each one of them!

* Being a client guy myself, I will not ever mention live gadgets here again (famous last words). To find out more about them visit these pages: 1 , 2 , 3 , 4.

* SideShow is a platform that attracts me hugely but I will refrain from talking about those gadgets until after Tech Ed Europe, in November (I am hoping to own hardware then and, if not, I'll just have to use the emulator - either way, stay tuned!).

* This leaves us with Sidebar gadgets... but that is the subject of my next post :-p

Winqual

Tue, October 10, 2006, 02:25 PM under Windows | Vista
Whenever I talk about the Vista enhancements in Windows Error Reporting, I am surprised to discover the number of devs that ask me "What is winqual?”

You know how sometimes an application crashes and then you hit that "send" button in the dialog that pops up? Well guess where it sends those reports (which can include your own diagnostics!).

That isn't just "a server that Microsoft uses to diagnose potential system issues". It is a server with data about *your* application, waiting for *you* to examine that data. Simply go register for free on winqual.

If you fix a bug and want to update all those users that have been hitting "send", how do you update them? Yup, winqual again. Trust me; it will make them happy :)

So what are you waiting for, use the Vista enhancements, register with winqual for free, examine the bug reports, and update your users with the solution. Let me hear you repeat after me (am I taking this too far?):
"I am off to http://winqual.microsoft.com/"



Vista: UAC internals

Sun, October 8, 2006, 03:15 AM under Windows | Vista | UAC
I have explained before what you (a managed developer) has to do about User Account Control in Vista (and also expanded a bit on UAC policies).

The other day I got asked exactly how this works under the covers. Luckily, my mate Kenny covers this on his article (butchered quote):
When an administrator logs on to a computer ... the system ... creates ... two different tokens representing the same logon session. The first token grants all the permissions and privileges afforded to the administrator while the second token is a restricted token ... offering far fewer permissions and privileges. ... The system then creates the shell application using the restricted token.

Follow this link for the full unedited story.

Problem fixed...

Fri, October 6, 2006, 01:36 AM under Windows | Vista
When I booted up my laptop today, with no intervention on my behalf, an unobtrusive message in a balloon on the tray informed me that there were solutions to my problems (or words to that effect, I doubt Vista can do anything about my real problems :)). So I clicked on it and it took me to the Problem Reports and Solutions window! See it below:



When I click on the "Problem fixed in Windows Vista final release" link, it take me to another page that looks like this (screenshot).

On that last screenshot, when I click on "See related problems" it shows me exactly what problem it is talking about, as you can see below:


If I then double-click on the item in the listview it takes me to the bucket/info that was sent up to winqual and thus it closes the loop (screenshot).

Have I told you that I love the new WER architecture more and more every day :)

ApplicationRecoverCallback

Wed, October 4, 2006, 04:36 AM under Windows | Vista
At a talk last week, while demoing the Vista application recovery mechanism, a delegate (no pun intended!) asked me if he could access UI elements (e.g. textbox contents) from the recovery function (i.e. in my sample, the RecoveryIt method).

The stock answer is that in your recovery method you should not be spending too much time doing anything and should make no assumptions for any application state as you have just crashed and hence who knows what is valid and what not. Try and do something that is fairly autonomous.

Having said that, from trial and error, I can tell you that you can write to files (as the sample shows), you can create threads, access private variables (and hence navigate object structures) and even the form's handle is valid.

Note that the method runs on a worker thread (that is donated by the OS in the recovery scenario); it is easily provable by sticking the following line of code in the recovery method:
MessageBox.Show(Thread.CurrentThread.IsBackground.ToString()); //true

So, based on the previous sentence, it is obvious that you cannot touch UI elements from that method (we know that we have to be on the main thread to do that). Even if you try to use Invoke/BeginInvoke, you still won't get very far. The point here is that you should treat the UI as frozen or in other words don't rely on the availability of a message pump...

Also, here is an extract of the bullet points from the slide that accompanies my demo:
+ Recovery routine called after data collection
--+ Application’s code attempts to recover user work
----+ Flush to disk, repair on next run of application
----+ Repair data in memory, save to disk

Hope this helps.

Vista: WerRegisterFile

Mon, October 2, 2006, 05:52 AM under Windows | Vista
Did you know that on Vista you can add your own files to the reports of WER?

Here are some steps for achieving that.

1. Create a brand new VS2005 WinForms project on Vista and name it "WerRegisterFile". Add a button to the form and in its event handler stick the following:
    private void button1_Click(object sender, EventArgs e)
{
// simulate crash
Environment.FailFast("bye bye");
}
Build and run the project from the file system to observe WER in action
a) First windows checks if there is a solution to the problem (screenshot).
b) Then it asks the end user to confirm that they'd like to send the report (screenshot)
c1) it then (asynchronously) proceeds with sending the data (e.g. Version.txt, minidump.mdmp) to winqual (screenshot). Note: this can be instantaneous and capturing that screenshot required blistering mouse movement

c2) it then informs the user to close the program (screenshot). Note that if the app registers for restart, then you won't see this dialog and instead the application will re-launch itself :-)

Let's enhance the WER process by adding our own file to send to winqual:

2. In the form paste the following pinvoke declarations:
    internal const int WerRegFileTypeOther = 2;
internal const int WER_FILE_ANONYMOUS_DATA = 2;

[System.Runtime.InteropServices.DllImport("kernel32.dll", CharSet = CharSet.Auto)]
internal static extern int WerRegisterFile(string pwzFile, int regFileType, int dwFlags);
3. Anywhere in your project (e.g. form_load, form ctor, button_click etc) before the application crashes make the following call:
WerRegisterFile("danielmoth.txt", WerRegFileTypeOther, WER_FILE_ANONYMOUS_DATA);
4. Go to the build directory of your solution (e.g. bin\release) and create a file named "danielmoth.txt"

Now, when you rebuild and then run the exe form the file system, you'll observe the same screenshots /behaviour as above. So how can we inspect that our own file was sent (other than visiting winqual and checking there)? Well, with 'Problem Reports and Solutions' of course!

Find the entry for "WerRegisterFile" (check the date/time to verify that it was just generated). Click on it and you are presented with the following dialog (I've highlighted with the red arrow the evidence that our file was sent):


If you click on the "View a temporary copy of these files" then you get to view a copy of exactly what was sent.

That's all folks :)

Some quick notes:
i) Remember that if you don't have an internet connection, these reports are queued and you can still view them following the steps I outlined before

ii) If you replace step 1 at the top with the alternative crash I described here (steps a & b), then in the last screenshot where it reads "Problem Signature 09" instead of "FatalError" it would say "System.DivideByZeroException"

iii) In addition to crashes and hangs, you can create and submit reports for other events. Surf the relevant APIs by starting here at WerReportCreate and then examine the APIs in the ‘Remarks’ section (and if you create a cool demo with those please drop me a line!).

Vista: Problem Reports and Solutions

Sun, October 1, 2006, 08:59 AM under Windows | Vista
I've talked about Windows Error Reporting in Vista before, but I don't think I explained how to examine locally the reports that have been sent (or that are in a queue to be sent, since with Vista that is what happens when there is no network connection).

From the Control Panel, navigate to 'System and Maintenance' and click the option that reads "Problem Reports and Solutions". You should have a screenshot similar to the following:


I encourage you to explore all of those options on the left, for example if you select "View problem history", then you are presented with a list that I am sure you'll find interesting. On my machine it looks as follows (you can drill into each report further as we'll see in my next blog entry):


Another relevant UI worth exploring is the "Reliability Monitor"
(...from the 'System and Maintenance' click on 'Performance Information and Tools' and then click on 'Advanced Tools' from the left).

Support for development IDEs on Vista

Tue, September 26, 2006, 01:36 PM under Windows | Vista
I am never happy when I learn about Microsoft things after they have hit the public (I thought one of the perks of working here is that I get to hear about these things in advance). Anyway, that is probably (if not definitely!) my fault.

* So the good news is that VB6 is basically supported on Vista from both an IDE and a runtime perspective. I didn’t know that probably because I don’t have a personal interest, but no doubt good news for those still in that world.

* We have now opened up a Beta release of SP1 for VS2005 (I knew about this one). This will not address all VS2005 issues on Vista (I didn’t know that, but admittedly, the issues are minor).

* The big news however for many of you and I am sure this will be discussed widely over the next few days: Visual Studio .NET 2002 and VS.NET 2003 will not be supported on Windows Vista.

Feel free to discuss these here.

Vista: Power Aware

Tue, September 26, 2006, 12:00 AM under Windows | Vista
Vista has a great mobility story for both the end user and the developer. By "mobility" here I mean the mobile PC (i.e. laptop/notebook, tabletpc, umpc). If you followed my Vista links, you’ll have come across the top 10 developer calls to action and number 10 on the list is: build for mobility.

One of the features I call out at my developer sessions is being power aware. Nobody likes a mobile PC that overheats and more importantly one that quickly runs out of battery; so you don't want your application to be the culprit that users point the finger at. When the user changes to a "power saver" plan, your app should respect it. When the user has pulled the cable and is running on battery, respect it! “Respect” means acting accordingly and consuming fewer resources avoiding unnecessary cpu intensive activities and thus saving battery life. Doing that, will allow your users to use your app for longer :)

To read more about being power aware, please visit the following 3 links:
- There is an msdn page here.
- There is also a nice article by Neil Roodyn here.
- You can follow links from the msdn page to a great Visual Studio solution that demonstrates what you have to do (direct link to exe here).

Once you download the lab (from my 3rd link above), browse to "\VISTA_POWER_CS\Lab 4 completed" and open "Vista Power Management" project. When you run it, it looks like this. Check it out, it is good :-)

I usually demo a very tiny subset of what is shown there. So if you've been to one of my talks and want my inferior demo, you may download the zip here. Run it on Vista, change your power plan and watch how the application responds. Do the same by pulling your power cable (note: do not pull your power cable if you are on a PC instead of a mobile PC! :-))

Search sample

Sun, September 24, 2006, 07:40 AM under Windows | Vista
To programmatically use search, I've already mentioned that as a managed developer you should be looking at Catherine Heller's blog and nothing has changed. From there you can find a whole bunch of useful info including the relevant links to msdn and the windows sdk. I am not repeating them here 'cause I really want you to visit the source and learn :-)

So the point of this blog post is simply to share with you the sample I use in my sessions when demoing how to search from your applications. Download the zip here.

After you build the VS2005 solution, when you run the app, you'll see the following in the textbox:
SELECT <columns> FROM SYSTEMINDEX..SCOPE() [WHERE <predicates>]

To start with replace it with this (and hit the button to see the results in the datagrid):
SELECT "System.FileName", "System.Size", "System.DateModified", "System.ItemType" FROM SYSTEMINDEX..SCOPE() WHERE "Directory"='file:c:\Windows\System32' ORDER BY "System.ItemType"

As I said, to learn more about the OleDb provider connection string and the query syntax, follow links from my previous Vista Search blog post.

Glass nugget

Fri, September 22, 2006, 07:55 AM under Windows | Vista
By now you know about the MSDN nuggets, of course.

Well, they finally published the one I did on Vista glass so you can watch/download it following the instructions from the link above.

This is a superset to the one I did for channel9. The additional 7 minutes are there to describe the feature and for a couple of slides (that I stripped out from the channel9 version).

Please note that, since Vista RC1, achieving glass through the TransparencyKey does not work anymore for Windows Forms (so ignore those 3 minutes in the video). The other two approaches are fine though :-)

Finally, for an overview of the DWM APIs see Greg Schechter's post.

Vista SKUs

Fri, September 22, 2006, 02:26 AM under Windows | Vista
Someone asked me about the different Windows Vista editions and what will be included in each one and I promised an answer on this blog...

If you download the product guide (item 1 link from here) you'll find section 2 dedicated to this topic (start at page 7).

First it describes the 6 SKUs as follows:
For Consumers: Home Basic, Home Premium, Ultimate
For Business: Business, Enterprise
For Consumer in Emerging Markets: Starter

You can then find a table on page 13 that summarizes the SKUs by customer segment, a table on page 14 that summarizes the SKUs by sales channel and a table on page 15 that compares the Windows XP SKUs with the Windows Vista SKUs.

Best of all, from page 16 to 20, there is a matrix of features against editions! (there may be an inaccuracy or two in there but overall it should give you a good head start before RTM).

Also of use may be these pages help and getready.

Vista: WFP and WER

Tue, September 5, 2006, 02:49 PM under Windows | Vista
Three weeks ago I wrote a short overview article of Windows Feedback Platform (WFP), the evolution of Windows Error Reporting (WER). Those of you who are subscribed to the msdn flash newsletter will have (hopefully) read it already (published 17th August). Its title: "Code quality, customer feedback and application reliability with Windows Vista".

If you want to read an online version of it (or wish to subscribe to the essential msdn flash) please go here where we store the archives.

In the article, I mention the Application Recovery APIs that I covered on my blog: RegisterApplicationRestart and RegisterApplicationRecoveryCallback.

If you've read those posts, you may wish to demo the APIs without having to explain WER and the dialogs that get thrown (I was in such a situation recently). One thing we can do is turn off WER for your sample demo application. To do that we need to wrap WerAddExcludedApplication like this:
[DllImport("wer.dll")]
internal static extern uint WerAddExcludedApplication(string pwzExeName, bool bAllUsers);


...and then call it like this:
WerAddExcludedApplication(AppDomain.CurrentDomain.FriendlyName, false);

Of course, if you do leave WER enabled, remember to show that with Windows Vista it now works even for hangs (not just for crashes) :-)

Vista UAC Security Policies

Mon, September 4, 2006, 05:20 PM under Windows | Vista | UAC
In the office today I was reading a popular PC magasine here in the UK and in the contents it said Dave (sorry I forget surname) looks at User Account Control in Windows Vista. I went to the page and read the article that left me quite disappointed. First, it doesn't really explain the goals behind UAC and how UAC achieves that: this information is available online (two clicks from my blog entry on User Account Control). Second, over half of the article is basically what seems to me a rant on the 'virtualization' feature (again, I cover virtualization on my UAC post). While I advise devs not to take advantage of virtualisation, I understand its purpose in offering crutches to some legacy applications that would otherwise break. In any case, the most disappointing thing about the article was that it didn't even mention how to turn off virtualization. While I did this at the nugget I link to from here, let's repeat it in written form.

1. In your Windows start menu go to the search box and type "sec" to bring up the "Local Security Policy"
2. Navigate to 'Security Settings->Local Policies->Security Options' and scroll to the bottom.
3. There you'll find 9 policies pertaining to User Account Control. Double click on the last one ("Virtualize file and registry write failures to per-user locations")
4. Change the value from Enabled to Disabled

With Vista RC1 there is an improvement to the dialogs that come up for each policy. There is an additional tab: "Explain". Click on this one to read about what the policy does :-) For the policy we've been talking about it looks like this:



I leave it to you to read the explanations for the other 8 policies:
- Switch to the secure desktop when prompting for elevation
- Run all users, including administrators, as standard users
- Only elevate UIAccess applications that are installed in secure locations
- Only elevate executables that are signed and validated
- Detect application installations and prompt for elevation
- Behavior of the elevation prompt for standard users
- Behavior of the elevation prompt for administrators in Admin Approval Mode
- Admin Approval Mode for the Built-in Administrator account

BTW, with RC1 (build 5600), the number of UAC prompts you get is significantly smaller than earlier builds so go check it out!

Vista: RegisterApplicationRecoveryCallback

Thu, August 24, 2006, 05:11 AM under Windows | Vista
We looked previously at RegisterApplicationRestart and that blog entry serves as the introduction to the Application Recovery APIs in Vista so I suggest you read that before continuing below.

To demo this, we'll start with the code we've already created.
f) For both samples, let's offer an additional user option for hanging the application. We can do this via a dedicated button like this:
    // hang
private void button3_Click(object sender, EventArgs e)
{
while (true) { }
}
g) Our pinvoke wrappers cover 3 functions RegisterApplicationRecoveryCallback, ApplicationRecoveryInProgress, ApplicationRecoveryFinished and a helper delegate as shown here:
    [DllImport("kernel32.dll")]
static extern uint RegisterApplicationRecoveryCallback(IntPtr pRecoveryCallback, IntPtr pvParameter, int dwPingInterval, int dwFlags);

[DllImport("kernel32.dll")]
static extern uint ApplicationRecoveryInProgress(out bool pbCancelled);

[DllImport("kernel32.dll")]
static extern uint ApplicationRecoveryFinished(bool bSuccess);

delegate int ApplicationRecoveryCallback(IntPtr pvParameter);
Taking advantage of the APIs involves two functions:
h) First, we register our interest to be called back, by passing in the method that must be called:
    private ApplicationRecoveryCallback mCallback;

// recover
private void button4_Click(object sender, EventArgs e)
{
mCallback = new ApplicationRecoveryCallback(this.RecoverIt);

IntPtr del = Marshal.GetFunctionPointerForDelegate(mCallback);

RegisterApplicationRecoveryCallback(del, IntPtr.Zero, 5000, 1 4);
}
i) Second, we need to write a method that will run our recovery code (I also used a helper method for code clarity):
    private int RecoverIt(IntPtr pvParameter)
{
// just an action that proves this runs
File.Create(Environment.CurrentDirectory + @"\recover.txt").Close();

int i = 4; //random number to simulate delay
while (i != 0)
{
bool b = this.Ping();
if (b) return 0;
Thread.Sleep(3000); //simulates some recovery action
i--;
}

ApplicationRecoveryFinished(true);
return 0;
}

private bool Ping()
{
bool esc;
ApplicationRecoveryInProgress(out esc);
if (esc)
{
MessageBox.Show("Cancelled");
}
return esc;
}
That's all there is to it. Now run your app, and after you have called RegisterApplicationRecoveryCallback, wait for 60 seconds before crashing/hanging the app via the appropriate button. Note how at that instance, in your application's folder an empty file is created (this is proof that your recovery method run).

The other relevant recovery functions that you could pinvoke are UnregisterApplicationRecoveryCallback and GetApplicationRecoveryCallback.
Incidentally, these restart and recovery APIs is what the new Restart Manager is based on.

channel9

Wed, August 23, 2006, 09:08 AM under Windows | Vista
...has my screencast on glass summarising my blog posts on the topic that regular readers will be familiar with. Go watch it!

...and this, this, this and that.

Vista: Application Recovery

Mon, August 21, 2006, 04:28 PM under Windows | Vista
Out of the many new native functions in Vista, two that I've been looking at using from managed code are the Application Recovery APIs.

There are 9 functions but two are the main ones: RegisterApplicationRestart and RegisterApplicationRecoveryCallback. These two serve two different, but complementary goals:
1. When your application crashes, it automatically restarts
2. When your application crashes, it gets a chance to save some recovery information

To demo this we need:
a) A new Windows Form application that has a button for crashing the application. Something like this:
// crash
private void button2_Click(object sender, EventArgs e)
{
int zero = 0;
int error = 5 / zero;
}
b) We must turn off .NET's exception handling. I've previously talked about global exception handling in .NET 2.0 but I never mentioned the ability to turn off plain exception catching, which we can do in our config file or in the Main function like this:
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
c) We then need to re-declare in managed code the RegisterApplicationRestart like this:
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
static extern uint RegisterApplicationRestart(string pszCommandline, int dwFlags);
Taking advantage of the API involves two lines of code in two different places.
d) First, we need to actually tell Vista that we want to be restarted (do this in your form_load or wherever else you see fit):
RegisterApplicationRestart("some_text_like_eg_pathname ", 0);

e) Second, on startup check if our application crashed last time (and use the string we passed to the API call):
string[] args = Environment.GetCommandLineArgs();
if (args.Length > 1)
{
this.Text = args[1];
}
Now run your app, and after you have called RegisterApplicationRestart, wait for 60 seconds before hitting the button that crashes your app. If you have windows error reporting enabled, you'll see the dialogs for checking for a solution, sending information and sending additional information. This is an interactive process where you can OK or cancel communications with winqual. Either way, once those dialogs are gone, your application will restart :-)

The other relevant restart functions that you could pinvoke are GetApplicationRestartSettings and UnregisterApplicationRestart.

In the next blog post, we'll look at the RegisterApplicationRecoveryCallback.

Using Vista's search in your managed apps

Wed, August 16, 2006, 04:41 AM under Windows | Vista
In an internal conversation, someone indicated they were interested in using “search” from their application. There are two great sources for that:

Catherine’s blog entries and Ian’s screencast.
--
UPDATE: Also see a search sample

Vista glass answers and DwmEnableBlurBehindWindow

Fri, August 11, 2006, 06:06 PM under Windows | Vista
While I have explained how to get glass on Vista with C# (twice), I did leave two open questions (hint: read the last paragraph of my last glass blog post or the stuff below won't make any sense).

Kenny Kerr steps up to the challenge and answers both questions on his article here!
For the answer to "why black" scroll down to the "Painting" section under the form with the red blob on it. For the question of why R=G=B fails, scroll slightly further down under the "Can you see me" forms.

If you don't care about the answers to the questions I posed then still go read Kenny's entry for the excellent clarification on the terminology at the beginning of his article. Even if you are not interested in the answers, terminology or even glass, then go read it for the coverage of other DWM topics. Go!

The other thing Kenny covers is a relevant glass API that I haven't talked about here before: DwmEnableBlurBehindWindow

I won't go into *any* description or give any context as I expect you'll read that on Kenny's blog. But after you've read the native approach, here is a simplified example of a managed version:

Create a new VS2005 winforms project on Vista, delete all Form1 files, add a new empty code file, and paste into it the following (then hit F5):
namespace GlassMoth
{
public class Form2 : System.Windows.Forms.Form
{
public Form2()
{
this.ClientSize = new System.Drawing.Size(200, 200);

System.IntPtr hr =
CreateEllipticRgn(30, 30, 170, 170); //or CreateRectRgn

DWM_BLURBEHIND dbb;
dbb.fEnable = true;
dbb.dwFlags = 1 2;
dbb.hRgnBlur = hr;
dbb.fTransitionOnMaximized = false;
DwmEnableBlurBehindWindow(this.Handle, ref dbb);
}

protected override void OnPaintBackground(
System.Windows.Forms.PaintEventArgs e)
{
e.Graphics.FillRectangle(
new System.Drawing.SolidBrush(System.Drawing.Color.Black),
new System.Drawing.Rectangle(30, 30, 140, 140));
}

#region pinvokes
[System.Runtime.InteropServices.DllImport("gdi32")]
private static extern System.IntPtr CreateEllipticRgn(
int nLeftRect, int nTopRect, int nRightRect, int nBottomRect);

public struct DWM_BLURBEHIND
{
public int dwFlags;
public bool fEnable;
public System.IntPtr hRgnBlur;//HRGN
public bool fTransitionOnMaximized;
}

[System.Runtime.InteropServices.DllImport("dwmapi")]
private static extern int DwmEnableBlurBehindWindow(
System.IntPtr hWnd, ref DWM_BLURBEHIND pBlurBehind);
#endregion
}
}
Enjoy (believe it or not, I do have one final blog entry to do on glass... stay tuned)!

Vista Windows Experience Index

Thu, August 10, 2006, 01:19 PM under Windows | Vista
Remember the System Performance Rating (the one of the M3)? It is now called Windows Experience Index. Here is the one from my M5 running build 5472.


--
UPDATE: Also see WinSAT

Fun with partitions and Vista 5472

Wed, August 9, 2006, 01:48 PM under Windows | Vista
This is kind of a rant but there may be some useful hidden info for some of you

About a month ago I made the mistake of letting some supposedly experts take my main laptop for 2 hours in order to put Vista 5472 on it (it later became the July CTP). It seemed like a good deal: They would preserve my existing XP installation and create a new partition where they install Vista including all relevant applications that I would put on anyway (e.g. Office 2007 B2TR and all internal utilities for VPN connecting etc). I thought they were going to save me time but when I collected the laptop they had "shot" my XP installation (not exactly shot, but it does blue screen on startup every time rendering it useless).

The other ‘clever’ thing they did was create my Vista partition as 20GB and leave the other one to 40GB+ contrary to what I explicitly asked for.

Anyway, I am not going to tell you that I love 5472 because quite frankly it doesn't work as well as Beta 2 did for me but that is probably due to Toshiba driver issues on the M5 and, besides, that is not the point of this blog post. So today I realised that I actually *really* do need more space on my boot drive.

Luckily, with Vista we get the ability out of the box to extend and shrink partitions. Go to 'Computer' and select 'Manage' to open the 'Disc Management' page. By right clicking on partitions the desired options are there. Great! I shrunk my D partition and that gave me 10GB of unallocated space. When I tried to 'Extend' my C drive though I got the error:
“There is not enough space available on the disk(s) to complete this operation.”

I read on this page that I could try the same operation from the command line, so I did and got this message:
“There is not enough usable free space on specified disk(s) to extend the volume.”

Given that I had 1GB of space and was only trying to extend by 1MB (for test purposes), that didn't seem right. I then played with the unallocated space by creating another drive letter and shrinking/extending it at will: so the feature works, it is just my C drive that can't be extended!

Here is a screenshot of what my setup looked like at the time:


I could bore you with the wasted hours trying to figure this out but it is summarised best here and here. So as you can see in the screenshot above, my C drive is on the end of the disc so it cannot be extended :(

I didn't give up. I thought "well, I am going to have to use Partition magic after all". Tried installing it and it complains about not being administrator. "UAC at work" me thinks. I disable UAC (as previously described here), reboot and I see a black screen informing me that the boot sector is corrupt - brilliant! After moments filled with panic, I managed to hunt down a Vista DVD, booted from that, selected the repair tools and waited with sweat dripping from my forehead while trying to remember the last time I performed a backup… eventually booting from the DVD fixed the problem - phew!!

Back online, I use my favorite search engine to see if it is a known issue and discover that the advice is not to use partition magic or other XP utilities with Vista. Doh!

If anybody has any idea how I can extend my C drive above I would welcome it. What I ended up doing is uninstalling a whole bunch of apps, and reinstalling them selecting D as the install drive. This moves me forward at the moment but is not ideal (plus I haven’t tested this configuration before and no doubt there will be issues with some apps).

The moral of the story: You can bet your life that when RC1 hits us in September, *I* will be the one installing it on my laptop and *not* some other %^$&^£*# person!

This cost me a full day. In hindsight, I could have spent the time repaving... Don't you wish that before starting a task something would tell you how long it will *really* take? [Sigh]

Glass in C#, an alternative approach

Sun, July 30, 2006, 03:46 PM under Windows | Vista
My blog post on extending Windows Vista's glass into the client area of managed applications seems to have drawn a lot of attention (and some questions). If you haven't already, please read glass and C# (it assumes you are already familiar with Glass on Vista).

In that approach we looked at 5 steps. There is an alternative approach to extending glass with C# on Vista. The alternative approach has the same 1st and 2nd steps. The step that changes is the 3rd step: explicitly using a black brush to paint the extended area of the form in the form's paint event handler.

Rather than do that, do this:
3. Place a panel on the form's top edge, set the panel's BackColor to color X and then set the form's TransparencyKey to the same color X.

When you run the application, the area occupied by the panel will have the glass effect :-)

Note that just using the BackColor of a panel combined with TransparencyKey of form, results in transparency (also applicable to WinXP). The fact that we do that on Vista in an area that we extended with DwmExtendFrameIntoClientArea, is what gives it the glass effect.

This approach of using panels and transparency was first described (afaik) by Tim Sneath here. If you read the comments on Tim's blog post you'll find a heap of unanswered questions regarding a fundamental problem: At runtime, clicking anywhere on the glass area, actually brings to the front the application behind it. In other words, there is true transparency i.e. inability to click on the glass area while retaining focus in this application.

The solution to the problem actually lies in what color you pick. Above I state that you should pick color X but I have not said what X must be. In Tim's example, he picked Gainsboro. If you look at Gainsboro it has the following values: R=220, G=220, B=220. The problem of the unwanted true transparency stems from the fact that all values are equal. So if you just change for example the R to be 221, then the problem goes away :-) Another gotcha if you create your own color is setting the Alpha of the color to anything but 255 (doing that will not render as glass).

So, now we have two approaches for achieving the same goal (I still prefer the explicit black painting) and you can download a project with the transparencykey approach here. Before I finish off, it is worth pointing out that when a window is maximized, any glass area appears black, which is the reason that most windows rendered fully in glass, do not offer a maximize button (to the dismay of Goths I guess :-p).



While from a practical point of view it all works, some of you will have open questions such as "why black?" and "what makes one color result in true transparency while another doesn't". I'll try to answer those in a future blog entry (if no one else beats me to it).
--
UPDATE: This one does not work post-RC1. See here

Vista: User Account Control

Sat, July 29, 2006, 02:30 PM under Windows | Vista | UAC
You, yes *you*, may not be gearing up to Windows Vista just yet but there is one core security element of Vista that IMO you must understand as soon as possible, and start working for it today on whatever Windows OS you are on. The feature in question is User Account Control. Please follow the links from item 5 here (it allows me a central place for updating resources).

Now that you've read those, I hope you understand UAC. In essence, when you set up user accounts on Vista, even if you set some of them as administrator, all interactive processes will run as standard user! The benefit is that any malicious code that gets on the user's machine also runs as standard user. If your applications require administrator privileges for some features, they will basically break on Vista (oversimplification aimed to scare you, but essentially true if you choose to ignore understanding UAC).

To work with this security feature, you must understand elevation, shields, virtualisation and security configuration options plus what you need to do programmatically for you applications to run on Vista. So, watch my nugget here or download it here to get the full picture...

There is one important bit of UAC that I do not cover in that short video (due to time): manifests. So after you’ve watched the video, come back and continue reading…

Fundamentally, on Vista you should declare that your app is aware of UAC (logo certification requirement). To do that you must embed a manifest in your application. Here are the steps on how to do that for managed applications in Visual Studio 2005 on Windows Vista:

1. Add to your VS2005 C# project this manifest file (replacing MyProjectNamewith your actual project name). Open the file in notepad and replace MyProjectNamewith your actual project name, same for description and Version.
2. Add this rc file to your project (replacing MyProjectName with your actual project name and removing the .txt extension). Open it with notepad and change MyProjectName to your actual project name.
3. Open your project file (csproj) in your favorite XML editor, scroll to the bottom and add/paste the following just before the closing Project element (replacing MyProjectNamewith your actual project name):
<propertygroup>
<win32resource>MyProjectName.res</win32resource>
</propertygroup>
<propertygroup>
<prebuildevent>"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\rc.exe" "$(ProjectDir)$(ProjectName).rc"</prebuildevent>
</propertygroup>

4. Rebuild!

The big clue that this has worked for you, apart from no compilation errors, is that virtualization gets turned off for your app (regardless of the security policy setting, which I show in my nugget). Try writing to HKLM and watch it fail with the manifest and succeed without.

If you change the level attribute of the requestedExecutionLevel element in the manifest from asInvoker to requireAdministrator, then you'll get the elevation prompt at startup (do this only if your app is explicitly aimed at administrators).
--
UPDATE: Also see this

Screencast on TaskDialog, CommandLink, cue banner

Sat, July 29, 2006, 02:20 PM under Windows | Vista
Regular readers will have read my previous blog entries on TaskDialog and TaskDialogIndirect. For the full C++ story on TaskDialog in depth read this.

You will have also read about CommandLink, TextBox cue banner and VistaBridge (that also includes the new CommonFileDialog).

Now you can enjoy all that in a short video I created (especially useful for seeing the above in action for those of you not running Windows Vista yet).

Watch it here (wmv) or download it here (zip).

Vista: CommandLink Button

Thu, July 13, 2006, 08:57 PM under Windows | Vista
I've been holding back on talking about CommandLink (and other Vista features) becuase I have been waiting for my "productions" to appear on msdn. By productions I mean a few short videos recorded with Camptasia... by the time they have been through bureaucracy cubed though, Vista will probably be on version 3.. LOL.. anyway..

CommandLink is a new style of button in Vista. If you want to see what it looks like, take a trip back to my TaskDialog post.

If you followed the link, you saw those squares with a green arrow and two pieces of text: "instruction" and "text". The "instruction" bit is the normal button text we know and love. The "text" bit is in smaller font and that is where you can add as much detail as you want about the button and its purpose. This is the text that typically today you have to place in a label next to the button or in the button's tooltip. Finally, although in my screenshot you can see the square rectangle around the button, when you hover the mouse away from the button, the rectangle fades away (harder to describe than to see which is why I was waiting for the video to go up before describing these).

Kenny Kerr (C++ guru) demonstrates how to do CommandLinks from native code in his msdn article.

Catherine Heller provided my colleague Eric Nelson here in the UK with some code that lets us use CommandLink from C# code. By bizarre coincidence (or is it outright plagiarism?) I use similar code in my Vista talks :-)

Get the CommandLinkButton code here and remember that this works on Windows Vista only.

My Vista System Performance Rating

Sat, July 8, 2006, 02:49 AM under Windows | Vista
I had a couple of people ask me after my Vista sessions
"What are you running it on? It seemed *very* fast!"
Since I haven't installed Beta 2 on my main laptop (Toshiba Tecra M5) yet, for all Windows Vista demos I still use an M3.

Best way to show the spec and what Vista thinks of it is to browse to Control Panel -> System and Maintenance -> Performance Rating and Tools.

Screenshot follows:

--
UPDATE: Also see Windows Experience Index

Vista: Glass in C#

Sat, June 17, 2006, 05:32 AM under Windows | Vista
We looked at glass in Vista previously so please read that to make sure we are on the same page and using the same terminology... I'll wait...

Great, now that you are back, let's see how to get glass in our C# applications. For starters, if glass is supported and enabled on the user's PC, then your non-client area will by default get the glass effect. In other words, the titlebar and borders will have glass (nothing more for you to do). The question is how to extend that into the client area like other OS applications do (as we saw last time).

There are 3+1 things we need to do:
1. Check that it is supported before proceeding further.
2. Extend the frame into the client area.
3. Paint the extended area black.

Optionally,
4. Allow the user to drag our window by pressing in the glass area as if they were pressing on the window's caption bar.

So let's go!

1. First, let's make sure we are not on a legacy OS:
    if (Environment.OSVersion.Version.Major < 6)
{
Debug.WriteLine("How about trying this on Vista?");
return false;
}
After that, we need to check that glass is enabled by using the DwmIsCompositionEnabled API which resides in Desktop Window Manager (dwmapi.dll)
    // [DllImport("dwmapi.dll")]static extern void DwmIsCompositionEnabled(ref bool pfEnabled);
bool isGlassSupported = false;
DwmIsCompositionEnabled(ref isGlassSupported);
return isGlassSupported;
2. Extending the frame requires setting up a margins structure and passing it to another DWM API: DwmExtendFrameIntoClientArea.

So if we want to extend a bit from the top of the window(i.e. we don't care about extending from the bottom, left or right sides) we can use the following code:
    // [DllImport("dwmapi.dll")]static extern void DwmExtendFrameIntoClientArea(IntPtr hWnd, ref Margins pMargins);
Margins marg;
marg.Top = 20; // extend 20 pixels from the top
marg.Left = 0;
marg.Right = 0;
marg.Bottom = 0;
DwmExtendFrameIntoClientArea(this.Handle, ref marg);
3. If you run your winforms app now, you'll find a black strip at the top. This is where we need the alpha blending and using a black brush does just that (tricking GDI that has no notion of an alpha channel).

So, in your form's paint event handler add the following code:
    SolidBrush blackBrush = new SolidBrush(Color.Black);
g.FillRectangle(blackBrush, 0, 0, this.ClientSize.Width, marg.Top);
4. Moving the form programmatically can easily be achieved by catching the mouse down/up/move events and some simple logic but instead we can use the following magic:
// make windows do the work for us by lieing to it about where the user clicked
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);

if (m.Msg == 0x84 // if this is a click
&& m.Result.ToInt32() == 1 // ...and it is on the client
&& this.IsOnGlass(m.LParam.ToInt32())) // ...and specifically in the glass area
{
m.Result = new IntPtr(2); // lie and say they clicked on the title bar
}
}

private bool IsOnGlass(int lParam)
{
// get screen coordinates
int x = (lParam << 16) >> 16; // lo order word
int y = lParam >> 16; // hi order word

// translate screen coordinates to client area
Point p = this.PointToClient(new Point(x, y));

// work out if point clicked is on glass
if (y < marg.Top)
return true;

return false;
}
5. There is no 5 :-) Just as a gotcha, if you decide to extend the client frame after the form has been displayed (and hence its handle has been created), you should call
this.RecreateHandle();

Note that there are other simpler approaches that use winforms Transparency but they seem to suffer from a very undesirable effect: When the user clicks on the glass area they are actually clicking on whatever is behind the form (true transparency is not what we want here).

Download a complete sample here.

Vista: Glass

Fri, June 16, 2006, 03:00 AM under Windows | Vista
One of the new "features" of Windows Vista is: glass. Title bars and borders on windows (i.e. the non-client area) now have a transparent glass effect. Assuming your graphics card is powerful enough to support it you must choose the "Windows Vista Aero" colour scheme under Appearance Settings and you've got glass ability:


If you don't have the aero option, go to "Control Panel-> System and Maintenance -> Performance Rating and Tools" and Refresh your rating [if even that doesn't do it for you, buy a better graphics card or lower your resolution or search the net but please do not email me for help in this particular area as this is all I know :-)]

You can control whether the glass effect is transparent or not (it looks good even when not transparent), and further control the intensity of it and the colour that the glass is based on. The control panel for these options looks like this:


While aesthetics is one of the goals that the glass effect scores, it achieves a usability goal that, admittedly, you only appreciate after living with Vista for a while: it makes you naturally focus on the content of the window, the main area, rather than anything else; it draws your attention to the solid, useful bit in the middle of the window.

Some applications have taken the aforementioned benefit further, by extending the glass effect into the client area of their windows. An example of that is the Control Panel, Document Explorer and Internet explorer (they have extended the glass area from the top of the window):


Another example is Windows Media Player (it has extended the glass from the bottom of the window):


And finally, the Sidebar Gadget Gallery has gone all the way as it has extended the glass from top to bottom (or bottom to top if you prefer):


Note that in all the previous applications/windows, you can move the window not only by holding down and moving the mouse on the title bar but also in any glass area. I don't know if this is a guideline but it should be (if it is, Windows Photo Gallery doesn't follow it). A few applications offer the ability to move a window by clicking on areas other than the title bar and it would be good to standardise on that area being glass. It would work the other way too by implicitly letting people know that "any glass area of a window can be used to drag the window".

So what is all this information doing on a developer blog? It simply provides background for when I show you how to use glass in your managed applications, next.

Vista: TaskDialogIndirect

Mon, June 12, 2006, 06:38 AM under Windows | Vista
You know about my simple managed wrapper of the simple version of the new TaskDialog API. I was going to go ahead and implement a wrapper for the advanced version (namely TaskDialogIndirect) but it seems that VistaBridge does that already).

I knocked up a new winforms app with a button that references the wrapper library, and I then setup as many options as I could on the TaskDialog. The results are ugly but do demonstrate some of the power of TaskDialog:


The code responsible for that follows:


Enjoy!

VistaBridge

Mon, June 12, 2006, 06:35 AM under Windows | Vista
You are a managed developer, with Vista Beta 2 and you also have the SDK (which you know from my Vista Links).

Now run (don't walk) to your Vista machine and do the following now:
Unszip [your drive letter]:\Program Files\Microsoft SDKs\Windows\v1.0\samples\CrossTechnologySamples.zip and browse to the VistaBridge folder and open the solution. If you have two projects in the solution then great, one of them is the Windows Presentation Foundation demo app. If one of the projects failed to load for you then you don't have the WPF Beta 2 bits installed. Not to worry though as the project that did load is the managed class library that you are interested in and it seems ok without the WPF bits. It wraps a few cool native APIs!

I found this by accident while searching my hard drive for one of my TaskDialog files but more on that next...

TextBox prompt

Sun, June 11, 2006, 06:44 PM under Windows | Vista
I just discovered "prompt" for textboxes (no medal required, thank you :-)).
The inspiration to dig into it was the mention in the Vista guidelines (scroll down to "Prompts").

So, you have empty textboxes and you need to prompt the user to do something and in some cases it makes sense to provide that prompt in the textbox while not making it part of the textbox text/content itself; when the user clicks on the textbox (gives it focus) or enters text into it, the prompt has to dissappear of course.

So if you have a windows form with a button and a textbox that has no text in it, put this code in the button_click event handler method:
Win32Api.SendMessage(
new HandleRef(textBox1, textBox1.Handle),
Win32Api.EM_SETCUEBANNER,
IntPtr.Zero,
"some prompt. click in the textbox to make me go away"
);
...and the constants you need are:
internal const uint ECM_FIRST = 0x1500;
internal const uint EM_SETCUEBANNER = ECM_FIRST + 1;
The good news seems to be that this is also available on XP, if we are to believe this msdn link.

It would be nice to have this feature on Windows CE so we could use it in our Windows Mobile applications where screen real estate is at a premium and having additional labels to describe the textbox is sometimes wasteful.

Vista: TaskDialog

Thu, June 1, 2006, 05:07 PM under Windows | Vista
One of the many new things in 'comctl32.dll version 6' is the TaskDialog.
A task dialog is similar to, while much more flexible than, a basic message box.

There are two variants of the TaskDialog the second of which is the one that gives you enormous flexibility and power. We will look at the first variant which, while being simpler, still offers advantages over the old MessageBox API :-)

When I say "look", what I mean is I will share my managed wrapper since TaskDialog is a native API only at this point.

First let's look at what the managed wrapper looks like in a Class Diagram (IWin32Window is part of the .NET Framework, of course):


Here is a VS2005 screenshot of intellisense when using our class:


My test harness looks like this:


And finally, here are a couple of screenshots of the end product:



You may download the sample project here (remember, this only works on Vista!).

Vista: Developer Resources

Sun, May 28, 2006, 05:30 PM under Windows | Vista
While many developers have been playing with various builds of Vista over the last 2 years, now that Vista Beta 2 is available, many more will start experiencing what is shaping up as the biggest release of Windows ever. I've captured below (in no particular order) some online resources to get you started.

If you have Vista site/blog which you think is of interest to developers, ping me with the URL and I may include it below.

1. Visit the 3 official sites that I link to from my Vista Beta 2 post. Then go download the Vista product guide.

2. Read the developer call to action: Top 10 things to do (TIP: on the left in the explorer view you can find 15+ additional articles to consume including the Application Compatibility Cookbook) and use the appcompat tools. Also keep an eye on the continuously updated developer story.

3. The Windows Software Development Kit (SDK) can be browsed online or downloaded locally.

4. With the next wave of technologies including Vista, you will hear the term User Experience (UX) being thrown about quite a bit. One element of that can be comprehended by reading the guidelines and understanding the aero aesthetics.

5. A controversial feature for some and essential for most, is the User Acount Control (UAC), which you should learn about immediately by reading here and here. In this context, some of you may need to understand COM Elevation Moniker.

6. Check out Gadgets that are a new type of task-specific "application" with a huge cool factor.

7. As you'd expect many presentations have been given about Vista. Download the presentations from the PDC 2005 and Mix06 conferences. Also sign up for the upcoming Vista webcasts.

8. Go view the Windows Vista channel9 videos.

9. For support, please visit the newsgroups and msdn forums. Other communities include DevReadiness.

10. There are a whole bunch of blogs dedicated to Vista (or at least with some strong content on it):
SDK Team , Network Access Protection , User Account Control , Vista Team , Tom Archer , Tim Sneath , Andre Da Costa , DWM

11. Here is a small selection of not-strictly-developer-focused Vista resources, as I reckon they will be of interest to some :-)
VistaBase , TweakVista , SuperSite , VistaMania

Vista: Beta 2 Available

Wed, May 24, 2006, 12:12 PM under Windows | Vista
Windows Vista, the next Windows client Operating System is due to ship in the second half of 2006 (with wide availability straight after Christmas).
It was previously code named Longhorn and, in fact, the server edition will not be named Vista and it still carries the Longhorn code name until the new name is announced.

We've come a long way since the first taste at PDC and now you can get Beta 2 of Vista. This is the first *public* Beta (i.e. not just for MSDN subscribers) and millions of downloads are expected. If you haven't already, you better check Vista out because your customers/users/competitors certainly will!

I can personally vouch that Beta 2 is a great improvement over the February CTP (build 5308) as I've been "playing" with both recently...

Go get Build 5384.4

While waiting for the download to complete, browse the totally revamped official Vista sites:
Vista on MSDN
Vista Home Page
Vista on TechNet