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

<channel>
	<title>Parks Computing &#187; Windows</title>
	<atom:link href="http://www.parkscomputing.com/labels/windows/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.parkscomputing.com</link>
	<description>Pedagogy for the autodidactic programmer</description>
	<lastBuildDate>Thu, 12 Jan 2012 22:48:30 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.4</generator>
		<item>
		<title>A Script to Find All Aliases for a Cmdlet</title>
		<link>http://www.parkscomputing.com/2011/03/a-script-to-find-all-aliases-for-a-cmdlet/</link>
		<comments>http://www.parkscomputing.com/2011/03/a-script-to-find-all-aliases-for-a-cmdlet/#comments</comments>
		<pubDate>Tue, 22 Mar 2011 01:04:24 +0000</pubDate>
		<dc:creator>Paul Parks</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[scripting]]></category>
		<category><![CDATA[software]]></category>

		<guid isPermaLink="false">http://www.parkscomputing.com/2011/03/a-script-to-find-all-aliases-for-a-cmdlet/</guid>
		<description><![CDATA[I&#8217;ve mentioned before that I love PowerShell, but I&#8217;m still trying to commit enough Cmdlets and aliases to memory that I can be immediately productive from a Powershell prompt without having to have a browser window open to the Powershell documentation on another monitor. Several of the Cmdlets may also be referenced through one or [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve mentioned before that I love <a href="http://technet.microsoft.com/en-us/library/bb978526.aspx">PowerShell</a>, but I&#8217;m still trying to commit enough <a href="http://www.bing.com/browse?g=powershell_cmdlets&amp;FORM=Z9GE22#toc=0">Cmdlets</a> and <a href="http://msdn.microsoft.com/en-us/library/ms714395(VS.85).aspx">aliases</a> to memory that I can be immediately productive from a Powershell prompt without having to have a browser window open to the Powershell documentation on another monitor. Several of the Cmdlets may also be referenced through one or more aliases, and it&#8217;s rather cumbersome to discover what aliases are defined for a given Cmdlet.</p>
<p>I stumbled onto a bit of code that will find all aliases for a given Cmdlet which I put it into a script named <code>Find-Alias</code>. That will let me type the following:</p>
<div class="example">
<pre>
<strong>PS C:\>Find-Alias Get-ChildItem</strong>

CommandType     Name                     Definition
-----------     ----                     ----------
Alias           dir                      Get-ChildItem
Alias           gci                      Get-ChildItem
Alias           ls                       Get-ChildItem
</pre>
</div>
<p>Here is the script code:</p>
<div class="example">
<pre>
param(
    [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipeLineByPropertyName=$true)]
    [string]$Command)

Process
{
  get-alias | where-object {$_.Definition -match $Command}
}
</pre>
</div>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.parkscomputing.com%2F2011%2F03%2Fa-script-to-find-all-aliases-for-a-cmdlet%2F&amp;t=A%20Script%20to%20Find%20All%20Aliases%20for%20a%20Cmdlet" id="facebook_share_button_610" style="font-size:11px; line-height:13px; font-family:'lucida grande',tahoma,verdana,arial,sans-serif; text-decoration:none; display: -moz-inline-block; display:inline-block; padding:1px 20px 0 5px; margin: 5px 0; height:15px; border:1px solid #d8dfea; color: #3B5998; background: #fff url(http://b.static.ak.fbcdn.net/images/share/facebook_share_icon.gif) no-repeat top right;">Share</a>
	<script type="text/javascript">
	<!--
	var button = document.getElementById('facebook_share_link_610') || document.getElementById('facebook_share_icon_610') || document.getElementById('facebook_share_both_610') || document.getElementById('facebook_share_button_610');
	if (button) {
		button.onclick = function(e) {
			var url = this.href.replace(/share\.php/, 'sharer.php');
			window.open(url,'sharer','toolbar=0,status=0,width=626,height=436');
			return false;
		}
	
		if (button.id === 'facebook_share_button_610') {
			button.onmouseover = function(){
				this.style.color='#fff';
				this.style.borderColor = '#295582';
				this.style.backgroundColor = '#3b5998';
			}
			button.onmouseout = function(){
				this.style.color = '#3b5998';
				this.style.borderColor = '#d8dfea';
				this.style.backgroundColor = '#fff';
			}
		}
	}
	-->
	</script>
	]]></content:encoded>
			<wfw:commentRss>http://www.parkscomputing.com/2011/03/a-script-to-find-all-aliases-for-a-cmdlet/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Supporting the Ribbon and Menus</title>
		<link>http://www.parkscomputing.com/2010/12/supporting-the-ribbon-and-menus/</link>
		<comments>http://www.parkscomputing.com/2010/12/supporting-the-ribbon-and-menus/#comments</comments>
		<pubDate>Tue, 28 Dec 2010 04:07:50 +0000</pubDate>
		<dc:creator>Paul Parks</dc:creator>
				<category><![CDATA[COM]]></category>
		<category><![CDATA[UI]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[ripsaw]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[IUIFramework]]></category>
		<category><![CDATA[IUIRibbon]]></category>
		<category><![CDATA[menu]]></category>
		<category><![CDATA[Ribbon]]></category>
		<category><![CDATA[Win32]]></category>

		<guid isPermaLink="false">http://www.parkscomputing.com/?p=262</guid>
		<description><![CDATA[How to support both the Ribbon and a traditional menu in a single executable and allow users to switch between them.]]></description>
			<content:encoded><![CDATA[<p>(I&#8217;ve posted a version of this article on <a href="http://www.codeproject.com/KB/menus/Ribbon_and_Menu_Support.aspx">Code Project</a>.)</p>
<p>I&#8217;ve finally come back to <a href="/labels/ripsaw/">Ripsaw</a>, in a round-about way. I&#8217;ve started working on the client application again as a way to investigate the <a href="http://msdn.microsoft.com/en-us/library/dd316910(VS.85).aspx">Windows Ribbon Framework</a>. Originally, I had planned to create a Ribbon implementation for Windows 7 and later, and a menu-based implementation for earlier Windows versions, or for users that preferred a menu over the Ribbon.</p>
<div id="attachment_265" class="wp-caption alignright" style="width: 279px"><a href="http://www.parkscomputing.com/wp-content/uploads/Scratch-Ribbon-Project.png"><img class="size-full wp-image-265  " title="Scratch Ribbon Project" src="http://www.parkscomputing.com/wp-content/uploads/Scratch-Ribbon-Project.png" alt="" width="269" height="197" /></a><p class="wp-caption-text">Scratch Ribbon Project</p></div>
<p>After I played around with the API a while, I realized it would be fairly simple to support both the Ribbon and the traditional menu in one executable. In this article I&#8217;ll describe a sample app that I put together that shows how to accomplish support for both command-selection methods.</p>
<p>(<a href="/code/Ribbon/ScratchRibbonProject.zip">Download the source code</a>)<br />
(<a href="/code/Ribbon/ScratchRibbonProject.exe">Download the executable</a>)<br />
(<a href="http://www.microsoft.com/downloads/en/details.aspx?familyid=A7B7A05E-6DE6-4D3A-A423-37BF0912DB84">Download the Visual C++ 2010 Redistributable</a>)</p>
<p><span id="more-262"></span></p>
<h2>A Few Words about the Ribbon</h2>
<p>The Ribbon was first introduced with Microsoft Office 2007 as a way to tame the huge menu and toolbar hierarchy that had evolved to present all of the suite&#8217;s features to its users. It then made its way into Windows 7 in the Paint and Wordpad applets, and can now be found in several third-party applications.</p>
<p>As with most things Microsoft does, it seems that users either love or hate the Ribbon. I happen to love it, since I&#8217;ve always disliked toolbars and I find menus clumsy, at best. Since everyone doesn&#8217;t share this opinion, and it&#8217;s relatively cheap to include a menu, and since I want to support XP, Vista, and Windows 7 with a single executable, I&#8217;ll try to satisfy as many people as I can by allowing users to select the command presentation method they prefer.</p>
<h2>The Project</h2>
<p>The application we&#8217;ll be working with began its life as an adaptation of <a href="http://blogs.msdn.com/b/oldnewthing/archive/2005/04/22/410773.aspx">a scratch program</a> that Raymond Chen uses as a framework for example programs in his articles. I adapted it to my own very thin C++ wrapper and added some things that I like to have in fully featured applications, then set about making it work with the Ribbon. You may <a href="/code/Ribbon/ScratchRibbonProject.zip">download the Visual C++ 2010 Express project</a> and follow along below.</p>
<h2>License</h2>
<p>There is no license. This code is public-domain code, and may be used in any manner without restrictions. I offer no guarantees or warranties at all.</p>
<h2>Prerequisites</h2>
<p>First of all, you&#8217;ll need <a href="http://www.microsoft.com/express/Windows/">Visual C++ 2010 Express</a> (which is free) or one of its more sophisticated versions (which are not free) in order to compile the project. If you prefer to use a different compiler you&#8217;ll have to adapt the code and project as necessary. You&#8217;ll also need the <a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyID=6b6c21d2-2006-4afa-9702-529fa782d63b&amp;displaylang=en">Windows 7 SDK version 7.1</a>. Finally, in order to see the Ribbon interface you&#8217;ll need to run the application on Windows 7 or on Windows Vista SP2 or later with the <a href="http://msdn.microsoft.com/en-us/library/ee663867(VS.85).aspx">Platform Update</a> installed. When the application runs on Vista SP1 or earlier it will only display the traditional menu.</p>
<h2>Configuring Visual Studio Projects for Ribbon Support</h2>
<p>Supporting the Ribbon in Visual Studio takes a little setup. First of all, once the SDK is installed, you need to change a setting in any new project in Visual Studio 2010 to take advantage of the SDK:</p>
<div id="attachment_284" class="wp-caption aligncenter" style="width: 628px"><a href="http://www.parkscomputing.com/wp-content/uploads/ScratchRibbonProject-Property-Pages.png"><img class="size-full wp-image-284 " title="Visual Studio Project Property Pages" src="http://www.parkscomputing.com/wp-content/uploads/ScratchRibbonProject-Property-Pages.png" alt="" width="618" height="475" /></a><p class="wp-caption-text">Choosing the Windows 7.1 SDK Platform Toolset in Visual Studio 2010</p></div>
<p>Next, you&#8217;ll need to add a new XML file to your project to contain your Ribbon markup. The Ribbon is defined by an <a href="http://msdn.microsoft.com/en-us/library/dd316913(VS.85).aspx">XML markup schema</a> described in detail on MSDN. This XML is compiled by a tool provided in the Windows 7.1 SDK, <a href="http://msdn.microsoft.com/en-us/library/dd316930(VS.85).aspx">UICC</a>. After you&#8217;ve added the XML file to your project, open the Property Pages for the file and change the &#8220;Item Type&#8221; property in the General properties to &#8220;Custom Build Tool.&#8221; Apply the setting, then in the Custom Build Tool&gt;General settings change the command line to something like the following:</p>
<div class="example">
<pre>"$(WindowsSdkToolsDir)\bin\uicc" "%(Identity)" "%(Filename).bin" /header:"%(Filename).h"
   /res:"%(Filename).rc2"</pre>
</div>
<p>Next, define the outputs from the UICC compiler in the &#8220;Outputs&#8221; property:</p>
<div class="example">
<pre>%(Filename).bin;%(Filename).h;%(Filename).rc2;%(Outputs)</pre>
</div>
<p>Make sure that you apply these changes for both the Debug and Release builds.</p>
<div id="attachment_296" class="wp-caption aligncenter" style="width: 628px"><a href="http://www.parkscomputing.com/wp-content/uploads/Ribbon.xml-Property-Pages.png"><img class="size-full wp-image-296 " title="Ribbon.xml Property Pages" src="http://www.parkscomputing.com/wp-content/uploads/Ribbon.xml-Property-Pages.png" alt="" width="618" height="475" /></a><p class="wp-caption-text">Changing the compiler settings for Ribbon markup in Visual Studio</p></div>
<p>Finally, you&#8217;ll need to add the output of the UICC compiler to the project&#8217;s main resource script. These need to go in a particular location in the resource file. In Visual Studio 2010 Professional, switch to the resource view (Ctrl+Shift+E), right-click on the resource script, and select &#8220;Resource Includes&#8221; from the context menu. Add the header file produced by UICC (for example, Ribbon.h) at the top in the &#8220;Read-only symbol directives&#8221; window, and add the resource script produced by UICC (for example, Ribbon.rc2) to the Compile-time directives window, as shown below:</p>
<div id="attachment_299" class="wp-caption aligncenter" style="width: 396px"><a href="http://www.parkscomputing.com/wp-content/uploads/Resource-Includes.png"><img class="size-full wp-image-299 " title="Resource Includes" src="http://www.parkscomputing.com/wp-content/uploads/Resource-Includes.png" alt="" width="386" height="447" /></a><p class="wp-caption-text">Visual Studio 2010 Professional resource includes window</p></div>
<p>In Visual C++ 2010 Express, you&#8217;ll need to edit the resource script code directly since there is no resource editor. Right-click on the resource script in the Solution Explorer and select &#8220;View Code&#8221; from the context menu. Find the TEXTINCLUDE sections and edit them as highlighted below:</p>
<div class="example">
<pre>#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//

1 TEXTINCLUDE
BEGIN
    "resource.h\0"
END

2 TEXTINCLUDE
BEGIN
    <span style="background-color: yellow;">"#include ""Ribbon.h""\r\n"</span>
    "#ifndef APSTUDIO_INVOKED\r\n"
    "#include ""targetver.h""\r\n"
    "#endif\r\n"
    "#define APSTUDIO_HIDDEN_SYMBOLS\r\n"
    "#include ""windows.h""\r\n"
    "#undef APSTUDIO_HIDDEN_SYMBOLS\r\n"
    "\0"
END

3 TEXTINCLUDE
BEGIN
    <span style="background-color: yellow;">"#include ""Ribbon.rc2"</span>"\r\n"
    "\0"
END

#endif    // APSTUDIO_INVOKED</pre>
</div>
<p>With these changes in place, the resource script will include the control IDs created by the UICC compiler so that you may reuse them in your menu resource.</p>
<h2>Running the Application</h2>
<p>As I mentioned earlier, this project began as a scratch application. The idea was to have a starting point for new applications that would provide a lot of the boring, boilerplate stuff so that I could concentrate on the interesting bits of new applications. Figuring out how to integrate the Ribbon and make it work was not entirely straightforward, which I found disappointing. The answers to my questions were usually somewhere out on the Internet, but never in one place. That&#8217;s why I decided to write this article to help those of you who might be having the same struggles I had.</p>
<p>After you&#8217;ve <a href="/code/Ribbon/ScratchRibbonProject.zip">downloaded the Visual C++ 2010 Express project</a>, open it in Express, build it, and run it. Or, if you prefer, just <a href="/code/Ribbon/ScratchRibbonProject.exe">download the executable</a> and run it. On Windows 7, and on Windows Vista SP2 or later with the <a href="http://msdn.microsoft.com/en-us/library/ee663867(VS.85).aspx">Platform Update</a> installed, you&#8217;ll see a window with a Ribbon control across the top. In the View tab of the Ribbon is a button that will allow the user to switch to a traditional menu bar. The View menu has a corresponding option to allow the user to display the Ribbon again. Most of the other commands will simply output a line of text in the client area describing the option that was selected.</p>
<div id="attachment_307" class="wp-caption aligncenter" style="width: 424px"><a href="http://www.parkscomputing.com/wp-content/uploads/Scratch-Ribbon-Project-menu-7.png"><img class="size-full wp-image-307 " title="Scratch Ribbon Project Menu on Windows 7" src="http://www.parkscomputing.com/wp-content/uploads/Scratch-Ribbon-Project-menu-7.png" alt="" width="414" height="263" /></a><p class="wp-caption-text">Scratch Ribbon Project Menu on Windows 7</p></div>
<p>On Windows XP, and on Windows Vista without the Platform Update, you&#8217;ll instead see a window with a traditional menu. The &#8220;Show Ribbon&#8221; menu option is disabled because the application detects that the Ribbon API is not supported on those platforms.</p>
<div id="attachment_308" class="wp-caption aligncenter" style="width: 299px"><a href="http://www.parkscomputing.com/wp-content/uploads/Scratch-Ribbon-Project-XP.png"><img class="size-full wp-image-308 " title="Scratch Ribbon Project XP" src="http://www.parkscomputing.com/wp-content/uploads/Scratch-Ribbon-Project-XP.png" alt="" width="289" height="179" /></a><p class="wp-caption-text">Scratch Ribbon Project on Windows XP</p></div>
<h2>Examining the Code</h2>
<p>I won&#8217;t go into too much detail about the usual Windows API elements of the code, or about the minimalist C++ framework it uses. I also won&#8217;t get into the details of the Ribbon markup, which is covered in detail in the <a href="http://msdn.microsoft.com/en-us/library/dd316913(VS.85).aspx">MSDN Ribbon documentation</a>. Instead, I&#8217;ll cover the bits of the code related to supporting the Ribbon and the menu.</p>
<p>The application&#8217;s initialization is performed in the <code>App::Initialize</code> method. The first order of business is initializing COM:</p>
<div class="example">
<pre>if (FAILED(CoInitialize(NULL)))
{
  ReportError(IDS_COINITIALIZE_FAILED);
  retVal = false;
  /* Fear of goto is highly irrational. Get over it. */
  goto exitinit;
}</pre>
</div>
<p>The comment about <code>goto</code> is a subject of another article entirely, so we&#8217;ll ignore that for now. It&#8217;s necessary to initialize COM because the Ribbon API is a set of COM objects that implement the various Ribbon interfaces (<code>IUIFramework</code>, <code>IUIRibbon</code>, etc.). A little further down in the initialization method the code reads the saved user settings, if they exist, then checks to see if the application should be using the Ribbon. The setting will be <code>true</code> by default, no matter what OS the application is running on, so the application will call the <code>CreateRibbon</code> method.</p>
<div class="example">
<pre>LoadAppSettings();

if (settings.isRibbon)
{
  CreateRibbon();
}</pre>
</div>
<p>The <code>CreateRibbon</code> method uses the Ribbon API&#8217;s COM objects to initialize and show the Ribbon.</p>
<div class="example">
<pre>bool App::CreateRibbon()
{
  /* Attempt to create the ribbon framework interface. */
  HRESULT hr = CoCreateInstance(
    CLSID_UIRibbonFramework,
    NULL,
    CLSCTX_INPROC_SERVER,
    IID_PPV_ARGS(&amp;pFramework));

  if (SUCCEEDED(hr))
  {
    /* Framework creation succeeded, so initialize the framework and
    create the ribbon. */

    /* The killRibbon flag controls the activation of message handling to fix a repaint
    problem that occurs when the ribbon is removed. */
    killRibbon = false;

    hr = pFramework-&gt;Initialize(GetHWND(), this);

    if (SUCCEEDED(hr))
    {
      hr = pFramework-&gt;LoadUI(GetModuleHandle(NULL), L"APPLICATION_RIBBON");

      if (SUCCEEDED(hr))
      {
        hr = pFramework-&gt;GetView(0, IID_PPV_ARGS(&amp;pRibbon));

        if (SUCCEEDED(hr))
        {
          settings.isRibbon = true;
        }
      }
    }
  }

  if (FAILED(hr))
  {
    /* If ribbon creation or initialization failed, make sure that any interfaces are released
    and set to null so that the UI will fall back and use the menu instead. */
    CloseRibbon();
  }

  return SUCCEEDED(hr);
}</pre>
</div>
<p>If the COM objects are created and their methods are called successfully, the API will remove the main window&#8217;s menu and display a Ribbon in its place. This method will fail on platforms that do not implement the Ribbon API, and since the application displays a menu on its main window by default, that menu will remain in place.</p>
<p>Next, the initial states of the various command options are set.</p>
<div class="example">
<pre>SetDirty(false);
SetRedo(false);
EnableMenuItem(GetMenu(GetHWND()), ID_SHOW_RIBBON,
  IsRibbonSupported() ? MF_ENABLED : MF_GRAYED);</pre>
</div>
<p>The <code>ID_SHOW_RIBBON</code> constant represents the menu selection that enables the Ribbon when the UI is displaying the menu bar. This function uses the return value of the <code>IsRibbonSupported</code> method to enable or disable the menu item. That method is implemented as follows:</p>
<div class="example">
<pre>bool App::IsRibbonSupported()
{
  bool isRibbonSupported = false;
  IUIFramework* pTmp = 0;

  /* Attempt to create the ribbon framework interface. */
  HRESULT hr = CoCreateInstance(
    CLSID_UIRibbonFramework,
    NULL,
    CLSCTX_INPROC_SERVER,
    IID_PPV_ARGS(&amp;pTmp));

  if (SUCCEEDED(hr))
  {
    isRibbonSupported = true;
    pTmp-&gt;Release();
  }

  return isRibbonSupported;
}</pre>
</div>
<p>All the method does is attempt to create a COM object provided by the Ribbon API. If the attempt fails, the method returns <code>false</code>. This will always fail on XP and on Vista without the Platform Update, unless of course some enterprising developer implements all the necessary COM interfaces and objects on those platforms.</p>
<h4>Implementing the COM Interfaces</h4>
<p>The Ribbon API requires an application using the Ribbon to implement two COM interfaces: <code>IUIApplication</code> and <code>IUICommandHandler</code>. The <a href="http://msdn.microsoft.com/en-us/library/dd371528(VS.85).aspx"><code>IUIApplication</code></a> interface defines callbacks into the application that are called by the Ribbon API. The <a href="http://msdn.microsoft.com/en-us/library/dd371491(VS.85).aspx"><code>IUICommandHandler</code></a> interface is called for each command that is exposed on the Ribbon.</p>
<p>The Scratch Ribbon Project implements both interfaces in the <code>App</code> object. This need not be the case, but it makes the shared implementation with the menu bar a little easier to accomplish. An alternative implementation would be to create a unique <code>IUICommandHandler</code> implementation for each command.</p>
<p>First of all, in the <code>App</code> class declaration in ScratchRibbonProject.h, the relevant methods are declared. The definitions are in ScratchRibbonProject.cpp, and we will examine each of them in turn.</p>
<p>First, we need to implement <a href="http://msdn.microsoft.com/en-us/library/ms680509(VS.85).aspx"><code>IUnknown</code></a> since all COM interfaces derive from this interface. The <code>AddRef</code> and <code>Release</code> methods are fairly straightforward.</p>
<div class="example">
<pre>ULONG STDMETHODCALLTYPE App::AddRef()
{
  return InterlockedIncrement(&amp;refCount);
}

ULONG STDMETHODCALLTYPE App::Release()
{
  return InterlockedDecrement(&amp;refCount);
}</pre>
</div>
<p>Next is <code>QueryInterface</code>, which should return a pointer to the requested interface if the object implements it.</p>
<div class="example">
<pre>HRESULT STDMETHODCALLTYPE App::QueryInterface(
  REFIID riid,
  void **ppvObject)
{
  if (!ppvObject)
  {
    return E_INVALIDARG;
  }

  if (riid == IID_IUnknown)
  {
    *ppvObject = static_cast&lt;IUnknown*>(static_cast<IUIApplication*>(this));
  }
  else if (riid == __uuidof(IUICommandHandler))
  {
    *ppvObject = static_cast&lt;IUICommandHandler*>(this);
  }
  else if (riid == __uuidof(IUIApplication))
  {
    *ppvObject = static_cast&lt;IUIApplication*>(this);
  }
  else
  {
    *ppvObject = 0;
    return E_NOINTERFACE;
  }

  AddRef();
  return S_OK;
}</pre>
</div>
<p>With that chore out of the way, we can move on to the interesting interfaces. The <code>IUIApplication</code> interface specifies three methods: <code>OnViewChanged</code>, <code>OnCreateUICommand</code>, and <code>OnDestroyUICommand</code>. The <a href="http://msdn.microsoft.com/en-us/library/dd371537(VS.85).aspx"><code>OnViewChanged</code></a> method is called by the Ribbon framework when the state of a Ribbon <a href="http://msdn.microsoft.com/en-us/library/dd371600(VS.85).aspx">View</a> changes. The <code>verb</code> parameter specifies the action performed by the view.</p>
<div class="example">
<pre>HRESULT STDMETHODCALLTYPE App::OnViewChanged(
  UINT32 viewId,
  UI_VIEWTYPE typeID,
  IUnknown* pView,
  UI_VIEWVERB verb,
  INT32 uReasonCode)
{
  HRESULT hr = E_NOTIMPL;

  if (UI_VIEWVERB_CREATE == verb)
  {
    IUIRibbon* pRibbon = NULL;
    hr = pView-&gt;QueryInterface(IID_PPV_ARGS(&amp;pRibbon));

    if (SUCCEEDED(hr))
    {
      LoadRibbonSettings(pRibbon);
      pRibbon-&gt;Release();
    }
  }
  else if (UI_VIEWVERB_SIZE == verb)
  {
    RECT rect = {};
    GetClientRect(GetHWND(), &amp;rect);
    OnSize(GetHWND(), 0, rect.right - rect.left, rect.bottom - rect.top);
  }
  else if (UI_VIEWVERB_DESTROY == verb)
  {
    IUIRibbon* pRibbon = NULL;
    hr = pView-&gt;QueryInterface(IID_PPV_ARGS(&amp;pRibbon));

    if (SUCCEEDED(hr))
    {
      SaveRibbonSettings(pRibbon);
      pRibbon-&gt;Release();
    }
  }

  return hr;
}</pre>
</div>
<p>The method is called with the <a href="http://msdn.microsoft.com/en-us/library/dd371588(VS.85).aspx"><code>UI_VIEWVERB_CREATE</code></a> and <code>UI_VIEWVERB_DESTROY</code> verb constants at Ribbon initialization and tear-down, respectively. This implementation uses those calls to load the ribbon settings when the Ribbon view is created and save them when it is destroyed. We&#8217;ll look at the <code>LoadRibbonSettings</code> and <code>SaveRibbonSettings</code> methods a little later on.</p>
<p>The <code>UI_VIEWVERB_SIZE</code> indicates that the Ribbon&#8217;s size has changed (for example, the ribbon has been minimized). The application may need to respond to this notification to adjust any other windows that need to be moved or resized based on the new Ribbon size. In this example, the method adjusts the client area by calling the <code>OnSize</code> message handler.</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/dd371531(VS.85).aspx"><code>OnCreateUICommand</code></a> method is called by the Ribbon framework for each command specified in the Ribbon markup. The application must return a pointer to an <code>IUICommandHandler</code> interface that will handle each particular command. In this application, all of the commands are serviced by the <code>App</code> object instance, so we just return  the requested pointer and increment the reference count.</p>
<div class="example">
<pre>HRESULT STDMETHODCALLTYPE App::OnCreateUICommand(
  UINT32 commandId,
  UI_COMMANDTYPE typeID,
  IUICommandHandler** commandHandler)
{
  if (commandHandler)
  {
    *commandHandler = static_cast&lt;IUICommandHandler*>(this);
    AddRef();
    return S_OK;
  }

  return E_INVALIDARG;
}</pre>
</div>
<p>The <a href="http://msdn.microsoft.com/en-us/library/dd371534(VS.85).aspx"><code>OnDestroyUICommand</code></a> method is called each time a command is destroyed. This would give the application an opportunity to clean up its command handlers, if necessary, but in our case there&#8217;s nothing to do.</p>
<div class="example">
<pre>HRESULT STDMETHODCALLTYPE App::OnDestroyUICommand(
  UINT32 commandId,
  UI_COMMANDTYPE typeID,
  IUICommandHandler* commandHandler)
{
  return E_NOTIMPL;
}</pre>
</div>
<p>Finally, we need to implement the two methods of the <code>IUICommandHandler</code> interface, which will be shared by all of the Ribbon commands in our application. The <a href="http://msdn.microsoft.com/en-us/library/dd371494(VS.85).aspx"><code>UpdateProperty</code></a> method is called by the framework to request an update to a command&#8217;s state. As an example of how to modify the enabled/disabled state, this application changes the state of the Save and Redo commands based on flags maintained by the <code>App</code> object.</p>
<div class="example">
<pre>HRESULT STDMETHODCALLTYPE App::UpdateProperty(
  UINT32 commandId,
  REFPROPERTYKEY key,
  const PROPVARIANT *currentValue,
  PROPVARIANT *newValue)
{
  if (newValue)
  {
    if (key.fmtid == UI_PKEY_Enabled.fmtid)
    {
      if (commandId == ID_CMD_SAVE)
      {
        (*newValue).boolVal = IsDirty() ? VARIANT_TRUE : VARIANT_FALSE;
      }
      else if (commandId == ID_CMD_REDO)
      {
        (*newValue).boolVal = CanRedo() ? VARIANT_TRUE : VARIANT_FALSE;
      }
    }
  }

  return S_OK;
}</pre>
</div>
<p>At last, we come to the method that connects activation of the Ribbon commands to actual application code. The <a href="http://msdn.microsoft.com/en-us/library/dd371489(VS.85).aspx"><code>Execute</code></a> is called with an <a href="http://msdn.microsoft.com/en-us/library/dd371563(VS.85).aspx">execution verb constant</a> of <code>UI_EXECUTIONVERB_EXECUTE</code> when the application needs to respond to a command event. This application posts a <a href="http://msdn.microsoft.com/en-us/library/ms647591(VS.85).aspx"><code>WM_COMMAND</code> message</a> equivalent to what would have been sent if the command had been selected from a menu. This, in turn, triggers the <code>WM_COMMAND</code> handler in the <code>WndProc</code> method.</p>
<div class="example">
<pre>HRESULT STDMETHODCALLTYPE App::Execute(
  UINT32 commandId,
  UI_EXECUTIONVERB verb,
  const PROPERTYKEY *key,
  const PROPVARIANT *currentValue,
  IUISimplePropertySet *commandExecutionProperties)
{
  if (verb == UI_EXECUTIONVERB_EXECUTE)
  {
    PostMessage(GetHWND(), WM_COMMAND, commandId, 0);
  }

  return S_OK;
}</pre>
</div>
<h4>The Ribbon XML</h4>
<p>The <a href="/code/Ribbon/Ribbon.xml">Ribbon.xml</a> file contains the markup that defines the application&#8217;s Ribbon. This file is compiled by UICC and included in the resource script. Each command has an <code>Id</code> attribute that specifies a numeric value sent to the application when the command is activated. This value is associated with the <code>Symbol</code> attribute in the Ribbon.h file generated by UICC. Following are the definitions for the &#8220;New&#8221; and &#8220;Open&#8221; commands:</p>
<div class="example">
<pre>&lt;Command Name="cmdNew" Id="0x0100" Symbol="ID_CMD_NEW" Keytip="N"&gt;
   &lt;Command.LabelTitle&gt;New&lt;/Command.LabelTitle&gt;
   &lt;Command.TooltipTitle&gt;New (Ctrl+N)&lt;/Command.TooltipTitle&gt;
   &lt;Command.TooltipDescription&gt;Create a new document&lt;/Command.TooltipDescription&gt;
   &lt;Command.LargeImages&gt;
      &lt;Image Source="images/New-icon-32.bmp" Id="101" Symbol="ID_NEW_LARGEIMAGE1" MinDPI="96" /&gt;
   &lt;/Command.LargeImages&gt;
   &lt;Command.SmallImages&gt;
      &lt;Image Source="images/New-icon-16.bmp" Id="102" Symbol="ID_NEW_SMALLIMAGE1" MinDPI="96" /&gt;
   &lt;/Command.SmallImages&gt;
&lt;/Command&gt;
&lt;Command Name="cmdOpen" Id="0x0103" Symbol="ID_CMD_OPEN" Keytip="O"&gt;
   &lt;Command.LabelTitle&gt;Open&lt;/Command.LabelTitle&gt;
   &lt;Command.TooltipTitle&gt;Open (Ctrl+O)&lt;/Command.TooltipTitle&gt;
   &lt;Command.TooltipDescription&gt;Open a document&lt;/Command.TooltipDescription&gt;
   &lt;Command.LargeImages&gt;
      &lt;Image Source="images/Open-icon-32.bmp" Id="103" Symbol="ID_OPEN_LARGEIMAGE1" MinDPI="96" /&gt;
   &lt;/Command.LargeImages&gt;
   &lt;Command.SmallImages&gt;
      &lt;Image Source="images/Open-icon-16.bmp" Id="104" Symbol="ID_OPEN_SMALLIMAGE1" MinDPI="96" /&gt;
   &lt;/Command.SmallImages&gt;
&lt;/Command&gt;</pre>
</div>
<p>When this XML is compiled, the following constants will be defined in Ribbon.h:</p>
<div class="example">
<pre>
#define ID_CMD_NEW 0x0100
#define ID_CMD_NEW_LabelTitle_RESID 60010
#define ID_CMD_NEW_Keytip_RESID 60011
#define ID_CMD_NEW_TooltipTitle_RESID 60012
#define ID_CMD_NEW_TooltipDescription_RESID 60013
#define ID_NEW_SMALLIMAGE1 102
#define ID_NEW_LARGEIMAGE1 101
#define ID_CMD_OPEN 0x0103
#define ID_CMD_OPEN_LabelTitle_RESID 60014
#define ID_CMD_OPEN_Keytip_RESID 60015
#define ID_CMD_OPEN_TooltipTitle_RESID 60016
#define ID_CMD_OPEN_TooltipDescription_RESID 60017
#define ID_OPEN_SMALLIMAGE1 104
#define ID_OPEN_LARGEIMAGE1 103
</pre>
</div>
<p>Most of these constants are used by various string and image resources, but the constants that will be used in the menu are <code>ID_CMD_NEW</code> and <code>ID_CMD_OPEN</code>.</p>
<h4>The Menu Resource</h4>
<p>Earlier, we modified ScratchRibbonProject.rc to include Ribbon.h so that the constants defined in that header by the Ribbon compiler could also used by the menu resource.</p>
<div class="example">
<pre>
IDC_APP_MENU MENU
BEGIN
    POPUP "&amp;File"
    BEGIN
        MENUITEM "&amp;New\tCtrl+N",                ID_CMD_NEW
        MENUITEM "&amp;Open\tCtrl+O",               ID_CMD_OPEN
        MENUITEM "&amp;Save\tCtrl+S",               ID_CMD_SAVE
        MENUITEM "Save &amp;As...\tCtrl+Shift+S",   ID_CMD_SAVEAS
        MENUITEM SEPARATOR
        MENUITEM "E&amp;xit\tAlt+F4",               ID_CMD_EXIT
    END
    POPUP "&amp;Edit"
    BEGIN
        MENUITEM "&amp;Undo\tCtrl+Z",               ID_CMD_UNDO
        MENUITEM "&amp;Redo\tCtrl+Y",               ID_CMD_REDO
        MENUITEM SEPARATOR
        MENUITEM "Cu&amp;t\tCtrl+X",                ID_CMD_CUT
        MENUITEM "&amp;Copy\tCtrl+C",               ID_CMD_COPY
        MENUITEM "&amp;Paste\tCtrl+V",              ID_CMD_PASTE
        MENUITEM "&amp;Delete\tDel",                ID_CMD_DELETE
    END
    POPUP "&amp;View"
    BEGIN
        MENUITEM "Zoom &amp;In\tCtrl+Plus",         ID_CMD_ZOOMIN
        MENUITEM "Zoom &amp;Out\tCtrl+Minus",       ID_CMD_ZOOMOUT
        MENUITEM "&amp;Normal Zoom\t Ctrl+0",       ID_CMD_NORMALZOOM
        MENUITEM SEPARATOR
        MENUITEM "&amp;Show Ribbon",                ID_SHOW_RIBBON
    END
    POPUP "&amp;Help"
    BEGIN
        MENUITEM "&amp;View Help\tF1",              ID_CMD_VIEWHELP
        MENUITEM "&amp;About\tCtrl+?",              ID_CMD_ABOUT
    END
END
</pre>
</div>
<p>The menu items defined in the menu resource now share the same numeric identifiers defined in Ribbon.xml. Activating any of these items, either on the Ribbon or the menu, will trigger the same handlers in the <code>OnCommand</code> message handler.</p>
<div class="example">
<pre>

void App::OnCommand(
  HWND hwnd,
  int id,
  HWND hwndCtl,
  UINT codeNotify)
{
  switch (id)
  {
  case ID_CMD_NEW:
    AppendText(L"New document\r\n");
    SetDirty(true);
    break;

  case ID_CMD_OPEN:
    AppendText(L"Open document\r\n");
    break;

    /* ... */
  }
}
</pre>
</div>
<h4>Swapping the Ribbon and the Menu</h4>
<p>When the application is run for the first time on a platform that supports the Ribbon, the application displays the Ribbon by default. Activating the Show Ribbon command on the View tab will cause the Ribbon to be removed from the window, and the menu bar will be shown in its place. The identifier for that command is <code>ID_HIDE_RIBBON</code>, and when it is activated the following code is executed in the <code>OnCommand</code> method:</p>
<div class="example">
<pre>
case ID_HIDE_RIBBON:
  /* I use PostMessage here because when I tried to remove the
  ribbon immediately after pressing the corresponding ribbon button,
  the UIRibbon code would die trying to process the WM_LBUTTONUP
  message on a ribbon window that no longer existed. This gets
  around that. */
  PostMessage(hwnd, AM_SHOW_MENU, 0, 0);
  break;
</pre>
</div>
<p>This puts the <code>AM_SHOW_MENU</code> message (an application-defined message) into the message queue, and that is handled by the following code in <code>App::WndProc</code>:</p>
<div class="example">
<pre>
case AM_SHOW_MENU:
  {
    /* Set this flag to trigger the repaint hack for DWM environments
    when the ribbon is removed. */
    killRibbon = true;
    CloseRibbon();
    PostMessage(GetHWND(), AM_RESTORE_MENU, 0, 0);
  }
  return 0;
</pre>
</div>
<p>This code sets a flag (<code>killRibbon</code>) to activate special message handling in order to work around some painting problems (which we&#8217;ll examine later). It then calls the <code>CloseRibbon</code> method.</p>
<div class="example">
<pre>
void App::CloseRibbon()
{
  /* If we have a ribbon, release it so that it will uninitialize cleanly. */
  if (pRibbon)
  {
    pRibbon->Release();
    pRibbon = 0;
  }

  /* Likewise, destroy and release the ribbon framework. */
  if (pFramework)
  {
    pFramework->Destroy();
    pFramework->Release();
    pFramework = 0;
  }

  settings.isRibbon = false;
}
</pre>
</div>
<p>This method releases the <code>pRibbon</code> object, if set, calls the <code>Destroy</code> method of the <code>pFramework</code> object, releases the <code>pFramework</code> object, and sets the pointers to null. Finally, it updates the <code>settings</code> object to note that the ribbon is not being used.</p>
<p>The last thing that the <code>AM_SHOW_MENU</code> handler does is post an <code>AM_RESTORE_MENU</code> message, which is handled as follows:</p>
<div class="example">
<pre>
case AM_RESTORE_MENU:
  {
    SetMenu(GetHWND(), hMenu);

    /* This is hackish, but it sets the menu items to the proper state. In a real app
    I'd probably use some sort of signal/slots implementation to wire up this stuff. */
    SetDirty(IsDirty());
    SetRedo(CanRedo());
    EnableMenuItem(GetMenu(GetHWND()), ID_SHOW_RIBBON,
      IsRibbonSupported() ? MF_ENABLED : MF_GRAYED);
  }
  return 0;
</pre>
</div>
<p>This restores the menu bar to the window with <code>SetMenu</code> and enables or disables the menu items as necessary.</p>
<p>Going the other direction, if the user selects the Show Ribbon option from the View menu, the <code>ID_SHOW_RIBBON</code> case in <code>OnCommand</code> is triggered.</p>
<div class="example">
<pre>
case ID_SHOW_RIBBON:
  PostMessage(hwnd, AM_SHOW_RIBBON, 0, 0);
  break;
</pre>
</div>
<p>This, in turn, activates a case in <code>WndProc</code>.</p>
<div class="example">
<pre>
case AM_SHOW_RIBBON:
  {
    if (IsRibbonSupported())
    {
      /* Don't need the repaint hack anymore. */
      killRibbon = false;

      ShowWindow(GetHWND(), SW_HIDE);
      CreateRibbon();
      ShowWindow(GetHWND(), SW_SHOW);

      RECT rect = {};
      GetClientRect(GetHWND(), &amp;rect);

      /* You aren't supposed to post a WM_SIZE message, but it's the only hack
      I could make work consistently to get the window to repaint correctly in
      all situations. */
      PostMessage(GetHWND(), WM_SIZE, 0,
        MAKELPARAM(rect.right - rect.left, rect.bottom - rect.top));
    }
  }
  return 0;
</pre>
</div>
<p>I ran into a number of painting problems in this code, and I eventually decided to just hide the window, restore the Ribbon, then show the window again. This is a little bit jarring, but until I can find a workaround for the painting problems it&#8217;s effective enough. (If you find a better workaround, please let me know.) I felt particularly dirty about posting a <code>WM_SIZE</code> message, but that was the only reliable way I could find to adjust the client area properly. When I saw that the same technique was used in WTL 8.0, I didn&#8217;t feel so bad anymore.</p>
<h4>Saving and Restoring Ribbon Settings</h4>
<p>Above, we saw that the <code>OnViewChanged</code> method calls <code>LoadRibbonSettings</code> when the Ribbon is initialized and <code>SaveRibbonSettings</code> when the ribbon is destroyed. The <code>SaveRibbonSettings</code> method creates an <code>IStream</code> object on a file in the user&#8217;s application data directory and passes that stream to the <a href="http://msdn.microsoft.com/en-us/library/dd371362(VS.85).aspx"><code>pRibbon->SaveSettingsToStream</code></a> method. The Ribbon framework will write its settings into this stream, after which the <code>SaveRibbonSettings</code> method releases the <code>IStream</code> and <code>IStorage</code> objects.</p>
<div class="example">
<pre>
bool App::SaveRibbonSettings(
  IUIRibbon* pRibbon)
{
  /* Build a path to an app-specific directory in the user's application
  data storage directory. */
  HRESULT hr = E_FAIL;
  WCHAR pPath[MAX_PATH] = {};

  if (BuildSettingsPath(pPath, L"ScratchRibbonProjectSettings.bin"))
  {
    IStorage* pStorage = 0;
    hr = StgCreateStorageEx(pPath, STGM_CREATE|STGM_SHARE_EXCLUSIVE|STGM_READWRITE,
      STGFMT_STORAGE, 0, NULL, NULL, __uuidof(IStorage), (void**)&amp;pStorage);

    if (SUCCEEDED(hr))
    {
      IStream* pStream = 0;

      hr = pStorage->CreateStream(L"Ribbon",
        STGM_CREATE|STGM_READWRITE|STGM_SHARE_EXCLUSIVE,
        0, 0, &amp;pStream);

      if (SUCCEEDED(hr))
      {
        hr = pRibbon->SaveSettingsToStream(pStream);
        pStream->Release();
      }

      pStorage->Release();
    }
  }

  return SUCCEEDED(hr);
}
</pre>
</div>
<p>At Ribbon initialization the <code>LoadRibbonSettings</code> opens the Ribbon stream in the file created by <code>SaveRibbonSettings</code> and passes it to <a href="http://msdn.microsoft.com/en-us/library/dd371361(VS.85).aspx"><code>pRibbon->LoadSettingsFromStream</code></a>. This will restore the previously saved state of the Ribbon.</p>
<div class="example">
<pre>
bool App::LoadRibbonSettings(
  IUIRibbon* pRibbon)
{
  HRESULT hr = E_FAIL;
  WCHAR pPath[MAX_PATH] = {};

  if (BuildSettingsPath(pPath, L"ScratchRibbonProjectSettings.bin"))
  {
    IStorage* pStorage = 0;

    hr = StgOpenStorageEx(
      pPath,
      STGM_READ|STGM_SHARE_DENY_WRITE,
      STGFMT_STORAGE,
      0, NULL, NULL,
      __uuidof(IStorage),
      (void**)&amp;pStorage);

    if (SUCCEEDED(hr))
    {
      IStream* pStream = 0;
      hr = pStorage->OpenStream( L"Ribbon", NULL,
        STGM_READ|STGM_SHARE_EXCLUSIVE,0, &amp;pStream);

      if (SUCCEEDED(hr))
      {
        LARGE_INTEGER liStart = {0, 0};
        ULARGE_INTEGER ulActual;
        pStream->Seek(liStart, STREAM_SEEK_SET, &amp;ulActual);
        hr = pRibbon->LoadSettingsFromStream(pStream);
        pStream->Release();
      }

      pStorage->Release();
    }
  }

  return SUCCEEDED(hr);
}
</pre>
</div>
<h4>Enabling and Disabling Ribbon Commands</h4>
<p>To demonstrate how to disable Ribbon commands, the Save and Redo commands will change state based on the other commands chosen by the user. The Save command is disabled until the New or Undo commands are activated, and the Redo command is disabled until the Undo command is activated.</p>
<p>The state of the Save command is controlled by a dirty flag set in the <code>App</code> object. If the current &#8220;document&#8221; is flagged as dirty, and therefore a candidate for a save operation, the Save command should be enabled. To set or clear the dirty flag the application calls the <code>SetDirty</code> method of the <code>App</code> object.</p>
<div class="example">
<pre>
void App::SetDirty(bool isDirtyInit)
{
  isDirty = isDirtyInit;

  if (pFramework)
  {
    pFramework->InvalidateUICommand(ID_CMD_SAVE, UI_INVALIDATIONS_STATE, NULL);
  }

  HMENU hMenu = GetMenu(GetHWND());

  if (hMenu)
  {
    EnableMenuItem(hMenu, ID_CMD_SAVE, isDirty ? MF_ENABLED : MF_GRAYED);
  }
}
</pre>
</div>
<p>This method modifies both the menu and Ribbon commands. It first checks to see if the <code>pFramework</code> pointer is non-null. If it is, it points to an instance of the <code>IUIFramework</code> interface implemented by the Ribbon API. It uses the pointer to call the <a href="http://msdn.microsoft.com/en-us/library/dd371375(VS.85).aspx"><code>InvalidateUICommand</code></a> method, specifying that the <code>ID_CMD_SAVE</code> command should be invalidated. This instructs the framework to call the application&#8217;s implementation of <code>IUICommandHandler::UpdateProperty</code>, which will set the state of the command based on the dirty flag.</p>
<h4>Various Clean-up Tasks</h4>
<p>All that we have left to cover are the various clean-up actions to restore the client area and handle some painting problems. First of all, there is a read-only edit control in the main window&#8217;s client area to display the descriptions of the selected Ribbon or menu commands. This control needs to be resized to fit around the Ribbon control when the main window is resized or the Ribbon size changes. This is accomplished by handling the <a href="http://msdn.microsoft.com/en-us/library/ms632646(VS.85).aspx"><code>WM_SIZE</code></a> message.</p>
<div class="example">
<pre>
void App::OnSize(
  HWND hwnd,
  UINT state,
  int cx,
  int cy)
{
  /* Adjust any child windows in the client area to match the new size. */
  AdjustClientArea(cx, cy);

  /* Hack to correctly repaint in DWM environments when the ribbon is removed. */
  if (killRibbon &amp;&amp; state != SIZE_MINIMIZED)
  {
    SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
      SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
  }
}
</pre>
</div>
<p>The <code>AdjustClientArea</code> function accepts the client width and height and adjusts the edit window to find around the Ribbon.</p>
<div class="example">
<pre>
void App::AdjustClientArea(
  int cx,
  int cy)
{
  /* Adjust the size of the edit window to fit into the client area.
  Take the size of the ribbon into consideration, if there is one. */
  UINT32 ribbonHeight = 0;

  if (pRibbon)
  {
    pRibbon->GetHeight(&amp;ribbonHeight);
  }

  SendMessage(hEdit, WM_SETREDRAW, 0, 0);
  MoveWindow(
    hEdit,
    0, ribbonHeight,
    cx,
    cy - ribbonHeight,
    TRUE);
  int textLen = GetWindowTextLength(hEdit);
  SendMessage(hEdit, EM_SETSEL, static_cast&lt;WPARAM>(textLen), static_cast&lt;LPARAM>(textLen));
  SendMessage(hEdit, WM_SETREDRAW, 1, 0);
  RedrawWindow(hEdit, NULL, NULL, RDW_ERASE | RDW_FRAME | RDW_INVALIDATE | RDW_ALLCHILDREN);
  SendMessage(hEdit, EM_SCROLLCARET, 0, 0);
}
</pre>
</div>
<p><code>AdjustClientArea</code> calls <a href="http://msdn.microsoft.com/en-us/library/dd742708(VS.85).aspx"><code>pRibbon->GetHeight</code></a> in order to get the height of the Ribbon, and then adjusts the size of the edit window accordingly.</p>
<p>The <code>OnSize</code> method also checks to see if the <code>killRibbon</code> flag is set. This flag is set when the user hides the ribbon and restores the menu. If the flag is set, <code>OnSize</code> calls <code>SetWindowPos</code> to trigger a <a href="http://msdn.microsoft.com/en-us/library/ms632634(VS.85).aspx"><code>WM_NCCALCSIZE</code></a> message.</p>
<p>There are also handlers for <a href="http://msdn.microsoft.com/en-us/library/ms632647(VS.85).aspx"><code>WM_SIZING</code></a> and <a href="http://msdn.microsoft.com/en-us/library/ms646274(VS.85).aspx"><code>WM_ACTIVATE</code></a> that check the <code>killRibbon</code> flag and call <code>SetWindowPos</code> if it is set. If it is not, they defer handling to <a href="http://msdn.microsoft.com/en-us/library/ms633572(VS.85).aspx"><code>DefWindowProc</code></a>.</p>
<div class="example">
<pre>
case WM_SIZING:
  {
    /* Hack to correctly repaint in DWM environments when the ribbon is removed. */
    if (killRibbon)
    {
      switch (wParam)
      {
      case WMSZ_TOP:
      case WMSZ_TOPLEFT:
      case WMSZ_TOPRIGHT:
        {
          PRECT pRect = reinterpret_cast&lt;PRECT>(lParam);
          SetWindowPos(GetHWND(), NULL,
            pRect->left, pRect->top,
            pRect->right - pRect->left, pRect->bottom - pRect->top,
            SWP_NOMOVE | SWP_NOZORDER | SWP_FRAMECHANGED);
        }
        break;

      default:
        DefWindowProc(GetHWND(), msg, wParam, lParam);
      }

      return TRUE;
    }

    return DefWindowProc(GetHWND(), msg, wParam, lParam);
  }

case WM_ACTIVATE:
  {
    /* Hack to correctly repaint in DWM environments when the ribbon is removed. */
    if (killRibbon)
    {
      if (wParam != WA_INACTIVE)
      {
        SetWindowPos(GetHWND(), NULL,
          0, 0, 0, 0,
          SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
      }

      return FALSE;
    }

    return DefWindowProc(GetHWND(), msg, wParam, lParam);
  }
</pre>
</div>
<p>The <code>WM_NCCALCSIZE</code> handler does some additional work to draw the frame correctly.</p>
<div class="example">
<pre>
case WM_NCCALCSIZE:
  {
    LRESULT result = DefWindowProc(GetHWND(), msg, wParam, lParam);

    /* Hack to correctly repaint in DWM environments when the ribbon is removed. */
    if (killRibbon &#038;&#038; wParam)
    {
      MARGINS margins = {};
      DwmExtendFrameIntoClientArea(GetHWND(), &#038;margins);

      RECT adjustedRect = {};
      AdjustWindowRectEx(&#038;adjustedRect, GetWindowStyle(GetHWND()),
        TRUE, GetWindowExStyle(GetHWND()));

      LPNCCALCSIZE_PARAMS pParams = (LPNCCALCSIZE_PARAMS)lParam;
      pParams->rgrc[0].top = pParams->rgrc[1].top + (-adjustedRect.top);
    }

    return result;
  }
</pre>
</div>
<p>When the Ribbon is restored, the <code>killRibbon</code> flag is cleared and normal processing occurs for these messages.</p>
<h2>Final Thoughts, Future Changes</h2>
<p>I only have a couple of annoyances with this code. First of all, I have to check the validity of each command message in <code>OnCommand</code> since the keyboard accelerators are not synchronized with the corresponding Ribbon commands as they would be with the menu. This is a minor complaint, though. The more annoying issue is that the ribbon graphics increase the size of the executable. For the users that prefer to use the menu this is a waste of memory, but I could get around that problem by keeping the Ribbon resources in a separate DLL. I haven&#8217;t tried implementing that yet, but I&#8217;ll post an update where when I do.</p>
<p>I&#8217;ve covered a lot of ground here, so please leave a comment if anything is still unclear.</p>
<p>Note: This project uses the <a href="http://www.iconarchive.com/category/system/must-have-icons-by-visualpharm.html">Must Have Icons</a> by <a href="http://www.visualpharm.com/">VisualPharm</a>.</p>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.parkscomputing.com%2F2010%2F12%2Fsupporting-the-ribbon-and-menus%2F&amp;t=Supporting%20the%20Ribbon%20and%20Menus" id="facebook_share_button_262" style="font-size:11px; line-height:13px; font-family:'lucida grande',tahoma,verdana,arial,sans-serif; text-decoration:none; display: -moz-inline-block; display:inline-block; padding:1px 20px 0 5px; margin: 5px 0; height:15px; border:1px solid #d8dfea; color: #3B5998; background: #fff url(http://b.static.ak.fbcdn.net/images/share/facebook_share_icon.gif) no-repeat top right;">Share</a>
	<script type="text/javascript">
	<!--
	var button = document.getElementById('facebook_share_link_262') || document.getElementById('facebook_share_icon_262') || document.getElementById('facebook_share_both_262') || document.getElementById('facebook_share_button_262');
	if (button) {
		button.onclick = function(e) {
			var url = this.href.replace(/share\.php/, 'sharer.php');
			window.open(url,'sharer','toolbar=0,status=0,width=626,height=436');
			return false;
		}
	
		if (button.id === 'facebook_share_button_262') {
			button.onmouseover = function(){
				this.style.color='#fff';
				this.style.borderColor = '#295582';
				this.style.backgroundColor = '#3b5998';
			}
			button.onmouseout = function(){
				this.style.color = '#3b5998';
				this.style.borderColor = '#d8dfea';
				this.style.backgroundColor = '#fff';
			}
		}
	}
	-->
	</script>
	]]></content:encoded>
			<wfw:commentRss>http://www.parkscomputing.com/2010/12/supporting-the-ribbon-and-menus/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>It&#8217;s Not a DOS Prompt!</title>
		<link>http://www.parkscomputing.com/2009/11/its-not-a-dos-prompt/</link>
		<comments>http://www.parkscomputing.com/2009/11/its-not-a-dos-prompt/#comments</comments>
		<pubDate>Sat, 14 Nov 2009 02:27:00 +0000</pubDate>
		<dc:creator>Paul Parks</dc:creator>
				<category><![CDATA[Windows]]></category>
		<category><![CDATA[rants]]></category>

		<guid isPermaLink="false">http://nightowl/?p=36</guid>
		<description><![CDATA[I&#8217;ve been hearing this a lot lately (you know who you are), so rather than pull all of you aside privately and give this lecture, I thought I&#8217;d do it once, publicly. You&#8217;re not running a DOS prompt. When you click on that shortcut that says, &#8220;Command Prompt&#8221; in Windows XP, or you run cmd.exe [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been hearing this a lot lately (you know who you are), so rather than pull all of you aside privately and give this lecture, I thought I&#8217;d do it once, publicly. You&#8217;re not running a DOS prompt.</p>
<p>When you click on that shortcut that says, &#8220;Command Prompt&#8221; in Windows XP, or you run <code>cmd.exe</code> from the &#8220;Run&#8221; box, you&#8217;re <em>not</em> starting a &#8220;DOS prompt.&#8221; What you are starting is a command line interface, or just &#8220;command line&#8221; if you prefer. If you haven&#8217;t actually run <code>COMMAND.COM</code>, <em>it&#8217;s not DOS!</em>.</p>
<p>So, please, next time don&#8217;t tell me to run your favorite utility &#8220;at the DOS prompt.&#8221; Let DOS rest in peace.</p>
<p>The first person to call Powershell a DOS prompt will get the lecture in real time.</p>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.parkscomputing.com%2F2009%2F11%2Fits-not-a-dos-prompt%2F&amp;t=It%27s%20Not%20a%20DOS%20Prompt%21" id="facebook_share_button_36" style="font-size:11px; line-height:13px; font-family:'lucida grande',tahoma,verdana,arial,sans-serif; text-decoration:none; display: -moz-inline-block; display:inline-block; padding:1px 20px 0 5px; margin: 5px 0; height:15px; border:1px solid #d8dfea; color: #3B5998; background: #fff url(http://b.static.ak.fbcdn.net/images/share/facebook_share_icon.gif) no-repeat top right;">Share</a>
	<script type="text/javascript">
	<!--
	var button = document.getElementById('facebook_share_link_36') || document.getElementById('facebook_share_icon_36') || document.getElementById('facebook_share_both_36') || document.getElementById('facebook_share_button_36');
	if (button) {
		button.onclick = function(e) {
			var url = this.href.replace(/share\.php/, 'sharer.php');
			window.open(url,'sharer','toolbar=0,status=0,width=626,height=436');
			return false;
		}
	
		if (button.id === 'facebook_share_button_36') {
			button.onmouseover = function(){
				this.style.color='#fff';
				this.style.borderColor = '#295582';
				this.style.backgroundColor = '#3b5998';
			}
			button.onmouseout = function(){
				this.style.color = '#3b5998';
				this.style.borderColor = '#d8dfea';
				this.style.backgroundColor = '#fff';
			}
		}
	}
	-->
	</script>
	]]></content:encoded>
			<wfw:commentRss>http://www.parkscomputing.com/2009/11/its-not-a-dos-prompt/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>An API is Forever</title>
		<link>http://www.parkscomputing.com/2009/05/an-api-is-forever/</link>
		<comments>http://www.parkscomputing.com/2009/05/an-api-is-forever/#comments</comments>
		<pubDate>Fri, 08 May 2009 18:36:00 +0000</pubDate>
		<dc:creator>Paul Parks</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[software]]></category>

		<guid isPermaLink="false">http://nightowl/?p=25</guid>
		<description><![CDATA[An API is an interface. Those of you that have worked with COM already know that once an interface is published, it can never, ever change. Ever. Not until the end of time. The reason is that some bit of code somewhere is going to be using that interface, and if you change it you&#8217;ve [...]]]></description>
			<content:encoded><![CDATA[<p>An <a href="http://en.wikipedia.org/wiki/API">API</a> is an <a href="http://en.wikipedia.org/wiki/Interface_(computer_science)">interface</a>. Those of you that have worked with <a href="http://en.wikipedia.org/wiki/Component_Object_Model">COM</a> already know that <a href="http://blogs.msdn.com/oldnewthing/archive/2005/11/01/487658.aspx">once an interface is published, it can never, ever change</a>. Ever. Not until the end of time. The reason is that some bit of code somewhere is going to be using that interface, and if you change it you&#8217;ve just broken that code. Of course, not changing an interface also means not deleting a portion of it.</p>
<p><span id="more-25"></span>(I apologize for the corrupted formatting of the code. I&#8217;m in the middle of a conversion from Blogger to WordPress.)</p>
<p>At my job I have worked on, and currently maintain, a few APIs implemented in Windows <a href="http://en.wikipedia.org/wiki/Dynamic-link_library">DLLs</a>, some of which have been around for a long time. I had to rewrite significant portions of the internal implementation of one particular DLL in order to add some new features, fix several bugs, and improve the overall performance of the DLL. The old API exposed from the DLL wasn&#8217;t able to take advantage of the new features, and it wasn&#8217;t designed all that well to begin with. Since nearly all of the use of that API was through a C++ template wrapper implemented a header, I just added a new set of API functions and changed the wrapper to use the new API.</p>
<p>I did some digging around in the code base (it&#8217;s a huge code base) to see what else was using the class wrapper around the DLL, and I found out that the component was in far more widespread use than I had anticipated. There were components in all corners of the code base using it now.</p>
<p>The component was still desperately in need of a new API, so what I did was write a new one and forward the old API to the new API. I changed the header file that declared the API functions to look like this:</p>
<div class="example">
<pre>FICTIONAL_API void NaDoStuff(   HANDLE hFict,   DWORD flags,    LPCSTR name,   LPCVOID bytes,    DWORD byteCount,   LPCSTR desc);

// The rest of the new API was declared here...// ...// ...

/************************************************************************Old, deprecated API. This API is still supported, but calls to all of these functions are now forwarded to the new API described above. Please use only the new API in new code.************************************************************************/

/* DEPRECATED: Use NaDoStuff instead. */FICTIONAL_API BOOL OaDoStuff(   HANDLE hFict,   DWORD flags,    LPCSTR desc,   LPCVOID bytes,    DWORD byteCount);

// The rest of the old API was declared here...// ...// ...</pre>
</div>
<p>I hoped that the comments would make clear that the use of the old API is discouraged, and that any clients should move to the new API. Likewise, in the implementation, I forwarded the old API functions to the new API functions:</p>
<div class="example">
<pre>FICTIONAL_API void NaDoStuff(   HANDLE hFict,   DWORD flags,    LPCSTR name,   LPCVOID bytes,    DWORD byteCount,   LPCSTR desc){   // Go do stuff}

// Elsewhere in the code..

FICTIONAL_API BOOL OaDoStuff(   HANDLE hFict,   DWORD flags,    LPCSTR desc,   LPCVOID bytes,    DWORD byteCount){   NaDoStuff(hFict, flags, "", bytes, byteCount, desc);   return TRUE;}</pre>
</div>
<p>In some cases, forwarding the old API to the new API meant that I had to make the new API implement the semantics of the old API whenever it was being called through the old API functions. For example, the old API had a nasty habit of writing sub-keys all over the company&#8217;s registry key under HKLM\SOFTWARE. I made the new API put these settings into a tidy sub-key that belonged to the API, like HKLM\SOFTWARE\ComanyName\Fictional. It would even hunt down the all of the old keys created by the old API and move them into the new sub-key. In a later story I&#8217;ll explain why I had to preserve that behavior in the old API, but for now just remember that I did.</p>
<p>Recently, a co-worker changed a customer-specific branch of the archive so that it would point to the newest implementation of this component. He was writing an application using some libraries that called this component&#8217;s API. He asked me to help with at a problem he was having, and when I went to look in the registry at some of the settings the API had written, I was dismayed to find that the settings were in the old location, all over the root of the company&#8217;s HKLM\SOFTWARE key. At first, I thought that he was still somehow using the old DLL, but when I checked the version information on the DLL it was, indeed, the new one. How could this be?</p>
<p>As I mentioned above, most clients use this DLL through a C++ wrapper, since most of the archive is now C++. Only a handful of older C modules call this API directly. The wrapper is a C++ template class, which means it is implemented in a header file. This customer archive was still pointing at the old version the header that called the old API. As I mentioned above, the new API preserves the semantics of the old API <span style="font-style: italic;">when it is called through the old API</span>, and that&#8217;s what we were seeing here.</p>
<p>My first suggestion, without really thinking about it, was to change the archive to point at the newer header. My co-worker pointed out that this would mean rebuilding <span style="font-weight: bold;">all</span> of the components in the archive that used the header, not just the one he was working on.</p>
<p>We left it alone, and everything is working as it should be. At some point in the future we&#8217;ll move all of the other components up to the newer version of the wrapper, and they&#8217;ll start seeing the behavior associated with the new API. In the meantime, the customer still benefit from a less buggy and more efficient component.</p>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.parkscomputing.com%2F2009%2F05%2Fan-api-is-forever%2F&amp;t=An%20API%20is%20Forever" id="facebook_share_button_25" style="font-size:11px; line-height:13px; font-family:'lucida grande',tahoma,verdana,arial,sans-serif; text-decoration:none; display: -moz-inline-block; display:inline-block; padding:1px 20px 0 5px; margin: 5px 0; height:15px; border:1px solid #d8dfea; color: #3B5998; background: #fff url(http://b.static.ak.fbcdn.net/images/share/facebook_share_icon.gif) no-repeat top right;">Share</a>
	<script type="text/javascript">
	<!--
	var button = document.getElementById('facebook_share_link_25') || document.getElementById('facebook_share_icon_25') || document.getElementById('facebook_share_both_25') || document.getElementById('facebook_share_button_25');
	if (button) {
		button.onclick = function(e) {
			var url = this.href.replace(/share\.php/, 'sharer.php');
			window.open(url,'sharer','toolbar=0,status=0,width=626,height=436');
			return false;
		}
	
		if (button.id === 'facebook_share_button_25') {
			button.onmouseover = function(){
				this.style.color='#fff';
				this.style.borderColor = '#295582';
				this.style.backgroundColor = '#3b5998';
			}
			button.onmouseout = function(){
				this.style.color = '#3b5998';
				this.style.borderColor = '#d8dfea';
				this.style.backgroundColor = '#fff';
			}
		}
	}
	-->
	</script>
	]]></content:encoded>
			<wfw:commentRss>http://www.parkscomputing.com/2009/05/an-api-is-forever/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

