Windows 7 Ribbon – Part 2 – How handle ribbon control events?

In this installement, let’s see how to handle the events of the ribbon control. I strongly reconmmend you to read the previous post on the basics of ribbon the way it’s being created. This is a continuation of the previous post.

To handle the events, the IUICommandHandler interface is implemented by the application and defines the Command handler methods for framework events.  The following function has to be implemented in the derived class.

Execute
Executes or previews the Commands bound to the Command hand`ler.

UpdateProperty
Sets a property value for a bound Command, for example, setting a Command to enabled or disabled depending on the state of a View.

For each Command in a View(Application.Views in the XML file), the Ribbon framework requires a corresponding Command handler in the host application. A new handler or an existing handler must be bound to the Command through the IUIApplication::OnCreateUICommand notification method.  This method is executed when the UI component is created. It’s possible create new command handler by querying IID_PPV_ARGS intefac. Any number of Commands can be bound to a Command handler.

The Command handler serves two purposes. First, it can update the values of properties for any command to which it is bound, such as setting a command to enabled or disabled. Second, it can execute or preview any commands to which it is bound.

In the previous instalment we’ve seen CRibbonImplementer class. So here we will be modifying the class. We’ll be creating the the handler

Step 1 – Include the generated .h file contains control IDs to the implementation .h/.cpp file of CRibbonImplementer

b1

Step 2 & 3 – Derive ribbon implementer class from IUICommandHandler and add the interface to COM Map

b2

Step 4 – Modify OnCreateUICommand function and add UI Handler on creating the control.

b3

Step 5 -  Add Execute handler to get notification when the button is clicked. This is like the normal message loop of a Win32 message loop system.b4

The final Step (6 ) – It’s necessary to implement IUICommandHandler::UpdateProperty as the base class doesn’t provide any implementations. We can leave this interface as unimplemented.

b5

The full Source code is given below. There’s no change in the other part of source code.


#include "stdafx.h"
#include <atlbase.h>
#include <atlcom.h>
#include <initguid.h>
#include <uiribbon.h>
// Step 1: Include menu ribbon resource.h
#include "MenuRibbonRes.h"

class CRibbonImplementer:
	public CComObjectRootEx<CComMultiThreadModel>,
	public IUIApplication,
	// Step 2: derive fromm IUICommandHandler
	public IUICommandHandler
{
public:
	BEGIN_COM_MAP(CRibbonImplementer)
		COM_INTERFACE_ENTRY(IUIApplication)
		// Step 3: IUICommandHandler add in teh COM Map
		COM_INTERFACE_ENTRY(IUICommandHandler)
	END_COM_MAP()

	STDMETHOD(OnCreateUICommand)(UINT32 nCmdID, __in UI_COMMANDTYPE typeID, __deref_out IUICommandHandler** ppCommandHandler)
	{
		// Step 4: IUICommandHandler
		// if my button is being created, the handler is created and attached
		if (nCmdID == cmdMyButton)
		{
			return QueryInterface(IID_PPV_ARGS(ppCommandHandler));
		}
		return E_NOTIMPL;
	}

	/* Step 5: Implement execute function.
		This function will be called on clicking
		the controls attached to command handler */
	STDMETHODIMP Execute(UINT nCmdID,
		UI_EXECUTIONVERB verb,
		__in_opt const PROPERTYKEY* key,
		__in_opt const PROPVARIANT* ppropvarValue,
		__in_opt IUISimplePropertySet* pCommandExecutionProperties)
	{
		HRESULT hr = S_OK;
		switch (verb)
		{
		case UI_EXECUTIONVERB_EXECUTE:
			if (nCmdID == cmdMyButton)
			{
				MessageBox(NULL, _T( "Clicked on My Button!" ),
					_T("My Button Execute"), MB_OK);
			}
			break;
		}    

		return hr;

	}

	// unimplemented methods
	// Step 6: Implement Update Property interface as well
	STDMETHODIMP UpdateProperty(UINT nCmdID,
		__in REFPROPERTYKEY key,
		__in_opt const PROPVARIANT* ppropvarCurrentValue,
		__out PROPVARIANT* ppropvarNewValue)
	{
		return E_NOTIMPL;
	}

	STDMETHOD(OnViewChanged)(UINT32 nViewID, __in UI_VIEWTYPE typeID, __in IUnknown* pView, UI_VIEWVERB verb, INT32 uReasonCode)
	{
		return E_NOTIMPL;
	}

	STDMETHOD(OnDestroyUICommand)(UINT32 commandId,
		__in UI_COMMANDTYPE typeID,
		__in_opt IUICommandHandler* pCommandHandler)
	{
		return E_NOTIMPL;
	} 

	STDMETHODIMP UpdateProperty(UINT nCmdID,
		__in REFPROPERTYKEY key,
		__in_opt const PROPVARIANT* ppropvarCurrentValue,
		__out PROPVARIANT* ppropvarNewValue)
	{
		return E_NOTIMPL;
	}
};

Visual Studio 2010 Tips – Zoom your source code as with Ctrl + Scroll mouse

One of the coolest thing in Visual Studio 2010 is the zoom source code functionality( I don’t know if there is any official name for it). As we’re doing with Office Word, any browsers, you can quickly zoom in/out your source code without the pain of going to Tools->Option Menu to change the font size.

Do it with following steps

1. Open your source code

2. Press Control + Scroll Up for Zoom-In the source code

3. Press Control+ Scroll Down for Zoom-Out the source code

 

See the image of a zoomed source code.

Zoom

Windows 7 Ribbon – Part 1 – How to Integrate a Simple Ribbon to your MFC Application?

The Office 2007 changed the the conventional menu to a new vibrant, beautiful, and useful(??) ribbons. After that many third party libraries (both commercial and non commercial) vendors provided components to integrate ribbons to our application. Finally Microsoft heed the MFC guys crying a loud to get support on ribbons. Microsoft included Ribbons and other office style controls with MFC Feature Pack for Visual Studio 2008.

The following figure depicts the anatomy of a typical Ribbon.

image

In the new version of Windows, Windows 7 , it supports ribbons natively and Microsoft allows us to create it using Ribbon Frame Work.  Few Accessories application like MS Paint, Wordpad etc. got UI lift with Windows Ribbons.

Developer can create ribbon using Ribbon Markup Language (similar to XML format). For the Windows Ribbon framework (Ribbon) to consume the Ribbon markup file, the markup file must be compiled into a binary format resource file. A dedicated Ribbon markup compiler, the UI Command Compiler (UICC), is included with the Microsoft Windows Software Development Kit (SDK) (7.0 or later) for this purpose. In addition to compiling the binary version of the Ribbon markup, the UICC generates an ID definition header file that exposes all markup elements to the Ribbon host application and a resource file that is used to link the binary markup to the host application at build time.

The workflow for the Ribbon is as follows

Ribbon-Flow

OK let’s create a simple ribbon step by step. You should have Windows 7 SDK installed and Visual Studio 2005 or above is required to compile this application. I’m taking a MFC Application do this instead of a Win32 application. I’m just creating a new MFC Dialog Based Application.

We can categorize the ribbon creation in to two categories.

  • XML Markup, used to define the Ribbon structure and organization of controls
  • C++ COM interfaces, used to initialize and handle events

Step 1: Create the XML file with your ribbon. Add this XML for the solution. The following XML is a simple ribbon contains the application a Tab,Group and a button inside it.

1


<Application xmlns="http://schemas.microsoft.com/windows/2009/Ribbon">
  <Application.Commands>
    <!--Commands for the whole ribbon-->
    <!--Tab name-->
    <Command Name="TabHome" Symbol="cmdTabHome" Id="30000" LabelTitle="Home"/>
    <!--Group under tab-->
    <Command Name="GroupMain" Symbol="cmdGroupMain" Id="30001" LabelTitle="Main"/>
    <!--button name and properties-->
    <Command Name="MyButton" Symbol="cmdMyButton" Id="30002" LabelTitle="My Button">
      <Command.TooltipTitle>My Button</Command.TooltipTitle>
      <Command.TooltipDescription>My Button</Command.TooltipDescription>
      <Command.SmallImages>
        <!--specify the bitmap. Only .bmp format is supported-->
        <Image Source="res/New.bmp"/>
      </Command.SmallImages>
    </Command>

  </Application.Commands>
  <Application.Views>
    <Ribbon>
      <!--organize the view-->
      <Ribbon.Tabs>
        <Tab CommandName="TabHome">
          <Group CommandName="GroupMain">
            <Button CommandName="MyButton" />
          </Group>
        </Tab>
      </Ribbon.Tabs>
    </Ribbon>
  </Application.Views>
</Application>

Step 2: Specify the custom build option for the XML file. The XML file has to be compiled with UICC.exe application. If Visual Studio can’t find the binary, locate it from your Microsoft SDK directory in program files and specify the path in the PATH variable. In the custom build rule, add following string as command line

uicc.exe MenuRibbon.xml MenuRibbon.bml /res:MenuRibbon.rc /header:MenuRibbonRes.h
 
Under the outputs specify the following string.

MenuRibbon.bml;MenuRibbon.rc;MenuRibbonRes.h
7

Step 3 – Add Support for ATL

Active template library (ATL) support is required to implement this functionality. In the project properties, specify ATL support as follows

6

Step 4 – Implement the IUIApplication interface for your application

It’s necessary to implement the IUIApplication interface for our application to support ribbons. I’ve wrapped inside a class for convenient use. Currently it’s not necessary to provide any implementation for derived interfaces.


#include "stdafx.h"
#include <atlbase.h>
#include <atlcom.h>
#include <initguid.h>
#include <uiribbon.h>

class CRibbonImplementer:
	public CComObjectRootEx<CComMultiThreadModel>,
	public IUIApplication
{
public:
BEGIN_COM_MAP(CRibbonImplementer)
COM_INTERFACE_ENTRY(IUIApplication)
END_COM_MAP()

	// unimplemented methods
	STDMETHOD(OnViewChanged)(UINT32 nViewID, __in UI_VIEWTYPE typeID, __in IUnknown* pView, UI_VIEWVERB verb, INT32 uReasonCode)
	{
		return E_NOTIMPL;
	}
	STDMETHOD(OnCreateUICommand)(UINT32 nCmdID, __in UI_COMMANDTYPE typeID, __deref_out IUICommandHandler** ppCommandHandler)      {          return E_NOTIMPL;      }      STDMETHOD(OnDestroyUICommand)(UINT32 commandId, __in UI_COMMANDTYPE typeID, __in_opt IUICommandHandler* pCommandHandler)
	{
		return E_NOTIMPL;
	}
};

class CRibbonHandler
{
private:
	IUIFramework* m_pFramework;

public:

	CRibbonHandler() : m_pFramework( 0 )
	{
	}
	~CRibbonHandler()
	{
		Destroy();
	}

	HRESULT Init( HWND hWnd)
	{
		HRESULT hr = ::CoCreateInstance(CLSID_UIRibbonFramework, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&m_pFramework));
		if(FAILED(hr))
			return hr;
		CComObject<CRibbonImplementer> *pApplication = NULL;
		hr = CComObject<CRibbonImplementer>::CreateInstance(&pApplication);
		if(FAILED(hr))
			return hr;

		hr = m_pFramework->Initialize(hWnd, pApplication);
		if(FAILED(hr))
			return hr;

		hr = m_pFramework->LoadUI(GetModuleHandle(NULL), _T( "APPLICATION_RIBBON"));

		return hr;
	}

	void Destroy()
	{
		if( m_pFramework )
		{
			m_pFramework->Release();
			m_pFramework = 0;
		}
	}
};

 

Step 5 – Integrate the output ribbon rc file and header with application resource.

Open the resource file (RiboonMFC.rc) file in source code mode. (right click on rc file and opt for “View Code”).

specify

#include “MenuRibbonRes.h”
#include “MenuRibbon.rc”

in application’s rc file

Step 6: Initialize COM and load the ribbon to the dialog

This operation can be done inside the app class of the application. Inside the InitInstance function, specify the following code. Note that we’re not calling DoModal inside the InitInstance but instead, we’re calling Create function of the dialog class and call RunModalLoop till user closes the dialog.


BOOL CRibbonMFCApp::InitInstance()
{
	CoInitialize( 0 );
// other initialization code can be put here like InitCommonControlEx etc.
	CRibbonMFCDlg dlg;
	m_pMainWnd = &dlg;

	CRibbonHandler ribbon;
	dlg.Create(dlg.IDD );

	HRESULT hr = ribbon.Init( dlg.GetSafeHwnd());
	if (FAILED(hr))
		return FALSE;

	dlg.RunModalLoop();

	return FALSE;
}

Now you’re done

Before compiling ensure that the bitmap specified for the ribbon button is existing in the solution file. Otherwise import it to the solution file.

You can see the application as follows if you successfully compiled your project We’ve not handled any events for the controls that we’ll learn in the next instalment.

8

Thought for the Day: Set Yourself Free!

Set yourself free from anything that might hinder you in becoming the person you want to be. Free yourself from the uncertainties about your abilities or the worth of your dreams, from the fears that you may not be able to achieve them or that they won’t be what you wanted.

Set yourself free from the past. The good things from yesterday are still yours in memory; the things you want to forget you will, for tomorrow is only a sunrise away. Free yourself from regret or guilt, and promise to live this day as fully as you can.

Set yourself free from the expectations of others, and never feel guilty or embarrassed if you do not live up to their standards. You are most important to yourself; live by what you feel is best and right for you. Others will come to respect your integrity and honesty.

Set yourself free to simply be yourself, and you will soar higher than you’ve ever dreamed.

- Edmund O’Neill

How to create a list from vector?

The following sample demonstrates, how to convert a vector to list(in other words, how to create a list from vector).

The simplest way is to iterate through all elements of container and add it to the destination container. the following snippet make use of std::copy function to copy contents from source to destination container. The destination and source iterator will be automatically incremented inside on each iteration. Before using this function you will have to ensure the destination container has enough room to hold the source elements. For that it may necessary to resize the container. See the snippet below. Note that you can use this technique with anu containers which supports iterator(actually that’s the purpose of std::copy function).


#include <iostream>
#include
	<list>
#include <vector>
#include <algorithm>

using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
	vector vec;
	// prepare the vector
	for (int i = 0; i < 10; i++ )
	{
		vec.push_back( i+1 );
	}

	// construct list with the size of vector
	list lis(vec.size());

	// iterate and copy the content to list
	copy( vec.begin(), vec.end(), lis.begin());

	// output the content to console
	copy( lis.begin(), lis.end(), ostream_iterator(cout, "\t" ) );

	return 0;
}

You 2.0

Download the You 2.0 Free E-Book

Original post by SourcesOfInsight blog.

Contents of Original post

You 2.0 is a way to unleash a version of your best self.  It cuts to the chase to help you quickly find your purpose, your why, your how, your values, your strengths, and your personal success patterns.  Once you’ve mapped these out, you have a firm foundation to be your best in any situation.  By finding and living your process, you lead a life by design, not by default.

I call it You 2.0 because it’s about renewal and taking yourself to the next level.  A few years back, a friend of mine broke his back.  You can imagine the extreme scenario.  Rather than focusing on trying to get back to where he was, he focused on rebuilding himself to be better and stronger than before.  A version 2.0.

Why You 2.0
Here are a some key benefits:

  • Success by design.  Rather than luck into success, you’ll know your personal combination for results.
  • Living your purpose.  Nothing fuels life like knowing what you want.
  • Living your values.  Living your values help you enjoy more moments in your life, a moment at a time. 
  • Playing to your strengths.  When you play to your strengths, you improve your energy, and you amplify your results.  It’s the simplest way to get more impact each day.
  • Improved results.  You’ll improve your results.  A little self-knowledge goes a long way.  You’ll be a better, faster, stronger you for whatever you want.

The real secret is life gets better once you have your personal map.

Download the Free You 2.0 E-Book
The You 2.0 E-Book is a very short (25 pages) guide to help you be YOUR best.

You20

How to reverse a string (using library function)?

Reversing a string is one of the first programs we write when we learn about loops. Anyway you don’t have to write the usual loop again to reverse a string. You can use _tcsrev ( _strrev ) function to reverse a character buffer. See the sample below


int _tmain(int argc, _TCHAR* argv[])
{
	TCHAR buff[] = _T( "Hello World!");
	_tcsrev( buff );
	_tcprintf( buff );
	return 0;
}

Squiggles Support in Visual C++ 2010

One of the best editor features I’ve enjoyed in Visual Studio Editor with C# environment is the real time highlighting of syntax and semantic errors etc using Squiggles (wavy underline). As native programmer, I wished a lot of we enjoy similar kind of helpful features with Visual C++ editor.

The new version of Visual C++ (coming with Visual Studio 2010) has implemented squiggles display in the source editor. Hovering over the squiggle displays compiler quality syntax/semantic errors. See the sample image below

Image Courteously – Visual C++ Team Blog

This is really a helpful feature as we don’t need to wait for finding the errors until the build and this can save lot of time. This feature is implemented atop (or make use) of intellisense. In my experience most of the large C++ projects are not directly using Visual Studio for building. If you’re directly using Visual Studio, you can benefit the entire features in a centralised manner. But the new features are certainly helps developers even if they’re using external build systems. The error list window will show the errors identified by the intellisense and this helps you to fix the issues before starting external build.

More technical details and information are available at Visual C++ team blog