Thursday, March 31, 2011

Qt Windows 7 extend frame into client area with transparency

I wanted to have something similar to these below:


Making the window transparent did not help me much. I was getting this:

I could not get rid of the margins.

After some research I figured out, and the result can be seen below:




To get merge the margins with the window frame it is enough to call DwmExtendFrameIntoClientArea with the margins value set to -1.

void ExtendFrameIntoClientArea(QWidget* widget) {
    MARGINS margins = {-1};

    DwmExtendFrameIntoClientArea(widget->winId(), &margins);
}


The transparency part is easy, it was published long time ago:

long EnableBlurBehindWidget(QWidget* widget, bool enable)
{
    HWND hwnd = widget->winId();
    HRESULT hr = S_OK;

    widget->setAttribute(Qt::WA_TranslucentBackground, enable);
    widget->setAttribute(Qt::WA_NoSystemBackground, enable);

    // Create and populate the Blur Behind structure
    DWM_BLURBEHIND bb = {0};

    bb.dwFlags = DWM_BB_ENABLE;
    bb.fEnable = enable;
    bb.hRgnBlur = NULL;

    DwmEnableBlurBehindWindow(hwnd, &bb);
    return hr;
}

I have managed to compile this using MINGW. The DwmEnableBlurBehindWindow and DwmExtendFrameIntoClientArea are loaded directly from dwmapi.dll.

#include <windows.h>

#define DWM_BB_ENABLE                 0x00000001  // fEnable has been specified

typedef struct _DWM_BLURBEHIND
{
    DWORD dwFlags;
    BOOL fEnable;
    HRGN hRgnBlur;
    BOOL fTransitionOnMaximized;
} DWM_BLURBEHIND, *PDWM_BLURBEHIND;

typedef struct _MARGINS
{
    int cxLeftWidth;      // width of left border that retains its size
    int cxRightWidth;     // width of right border that retains its size
    int cyTopHeight;      // height of top border that retains its size
    int cyBottomHeight;   // height of bottom border that retains its size
} MARGINS, *PMARGINS;

extern "C"
{
    typedef HRESULT (WINAPI *t_DwmEnableBlurBehindWindow)(HWND hWnd, const DWM_BLURBEHIND* pBlurBehind);
    typedef HRESULT (WINAPI *t_DwmExtendFrameIntoClientArea)(HWND hwnd, const MARGINS *pMarInset);
}

void DwmExtendFrameIntoClientArea(HWND hwnd, const MARGINS *pMarInset) {
    HMODULE shell;

    shell = LoadLibrary(L"dwmapi.dll");
    if (shell) {
        t_DwmExtendFrameIntoClientArea set_window_frame_into_client_area = reinterpret_cast<t_DwmExtendFrameIntoClientArea>(GetProcAddress (shell, "DwmExtendFrameIntoClientArea"));
        set_window_frame_into_client_area(hwnd, pMarInset);

        FreeLibrary (shell);
    }

}

void DwmEnableBlurBehindWindow(HWND hwnd, const DWM_BLURBEHIND* pBlurBehind) {
    HMODULE shell;

    shell = LoadLibrary(L"dwmapi.dll");
    if (shell) {
        t_DwmEnableBlurBehindWindow set_window_blur = reinterpret_cast<t_DwmEnableBlurBehindWindow>(GetProcAddress (shell, "DwmEnableBlurBehindWindow"));
        set_window_blur(hwnd, pBlurBehind);

        FreeLibrary (shell);
    }
}

The project can be downloaded from here.

Windows 7 Taskbar Extensions in Qt: Tab Thumbnails

In this post I'll explain how I implemented this Windows 7 feature using Qt with MINGW32.

For this purpose I have created a simple browser with tabs.


The main blockers implementing this using Qt with MINGW32 are the missing defintions of various important Windows 7 SDK functions, interfaces, enums, constants and structures (e.g. ITaskbarList3, ITaskbarList4, CLSID_TaskbarList, STPFLAG, DWMWINDOWATTRIBUTE, and DWM functions (DwmInvalidateIconicBitmaps, DwmSetIconicThumbnail, DwmSetIconicLivePreviewBitmap, DwmSetWindowAttribute)).

In order to fix this I had to define them mingw friendly in my project. The DWM functions are loaded during runtime from dwmapi.dll.

In the win7utils.h and win7utils.cpp you can see the final result.

Initializing

Firstly the program has to register the TaskbarButtonCreated message. This will create a taskbar button for this application. Without this it is impossible to use the new Windows 7 features.


After having the taskbar button created the application has to initialize an ITaskbarList3 or ITaskbarList4 interface in order to be able to access the new features.

In our event filter:

bool MyClass::eventFilter(void *message_, long *result)
{
    static unsigned int taskBarCreatedId = WM_NULL;

    MSG* message = static_cast(message_);

    if (taskBarCreatedId == WM_NULL) {
        taskBarCreatedId = RegisterWindowMessage(L"TaskbarButtonCreated");
        return false;
    }

    if (message->message == taskBarCreatedId &&
        message->hwnd == parent->winId()) 
        //very important to check to which window this message is address
        //since it is possible to get a dozen of them
        //the parent can be a QMainWindow or any other QWidget which acts as a 
        //tab container
    {
        //init the ITaskbarList3  interface
        //announce that the interface is ready
        return true;
    }
    //...
}



Adding tabs

The most important ITaskbarList3 functions to work with in this case are: RegisterTab, SetTabActive, SetTabOrder and UnregisterTab.

You should not register the window or widget which contains these tabs as a tab.

First thing to do is to capture all messages sent to the application. This can be achieved by substituting the current application's event filter with ours.
This will route all messages to our own function.

// MyClass.h
class MyClass {
//..
  static bool eventFilter(void *message_, long *result);
  static QCoreApplication::EventFilter m_oldEventFilter;
//..
};

//MyClass.cpp
QCoreApplication::EventFilter TabsManager::m_oldEventFilter = NULL;

MyClass::MyClass {
//..
   m_oldEventFilter = qApp->setEventFilter(&MyClass::eventFilter);
}

Before registering a widget as a tab it is necessary to set two attributes to the window handle. This can be achieved by setting the DWMWA_FORCE_ICONIC_REPRESENTATION and DWMWA_HAS_ICONIC_BITMAP to true:

void EnableWidgetIconicPreview(QWidget* widget) {
    BOOL enable = TRUE;

    DwmSetWindowAttribute(
        widget->winId(),
        DWMWA_FORCE_ICONIC_REPRESENTATION,
        &enable,
        sizeof(enable));

    DwmSetWindowAttribute(
        widget->winId(),
        DWMWA_HAS_ICONIC_BITMAP,
        &enable,
        sizeof(enable));
}

This code will make the application receive WM_DWMSENDICONICTHUMBNAIL and WM_DWMSENDICONICLIVEPREVIEWBITMAP messages when a thumbnail is requested for the registered widget.

Another important thing which is related to Qt, you SHOULD NOT REGISTER AS A TAB A WIDGET WHICH IS BEING USED IN THE MAINWINDOW OR DIALOG.
This will not work.
The solution is to create a new blank widget, register it, and map the real widget to this blank widget. The thumbnails in the taskbar will be provided by the real widgets but the messages will be addressed to the blank ones.

So each time when a WM_DWMSENDICONICTHUMBNAIL or WM_DWMSENDICONICLIVEPREVIEWBITMAP message is received, it is addressed to the blank registered widget, not the real one.

The steps:
1) Create a new QWidget*
2) Map this created QWidget to the real QWidget is being used. This is apt to you.
3) Set iconic preview enabled to the created QWidget
4) Register the created QWidget as a tab
5) Set tab order
6) Set it as the active tab

//ITaskbarList3*  m_taskbarHandler;
//QMap<WId, QWidget*> m_widgetMap;
//QWidget* m_parent;

void MyClass::addTab(QWidget* widget) {

    QWidget* tab_widget = new QWidget();

    //enable iconic preview
    EnableWidgetIconicPreview(tab_widget->winId(), true);

    //map it
    m_widgetMap[tab_widget->winId()] = widget;


    //register it
    m_taskbarHandler->RegisterTab(tab_widget->winId(), m_parent->winId());
    m_taskbarHandler->SetTabOrder(tab_widget->winId(), NULL);
    m_taskbarHandler->SetTabActive(NULL, tab_widget->winId(), 0);
}

Processing the received messages

In our own event filter we'll receive many messages, the most important ones are:

The message code provided by the RegisterWindowMessage function. When the "TaskbarButtonCreated" message was registered - When this happens our tab manager will initialize the ITaskbarList3 interface.

WM_DWMSENDICONICTHUMBNAIL - from MSDN: "instructs a window to provide a static bitmap to use as a thumbnail representation of that window."

WM_DWMSENDICONICLIVEPREVIEWBITMAP - from MSDN: "Instructs a window to provide a static bitmap to use as a live preview (also known as a Peek preview) of that window."

WM_ACTIVATE - when a thumbnail was clicked.

WM_CLOSE - when a thumbnail is about to be closed.

Providing the static bitmap

When a WM_DWMSENDICONICTHUMBNAIL message is received first thing it is checked if this is addressed to one of our registered widgets. This check can be done by comparing widget->winId() to message->hwnd. If they match we have to provide a static bitmap.
The created bitmap is set by calling the DwmSetIconicThumbnail function

Providing the live preview

Basically is almost the same as in the first case, except that the DwmSetIconicLivePreviewBitmap function is called.

An example:
case WM_DWMSENDICONICTHUMBNAIL:
     //check if this is message is addressed to one of our widgets
     if (!m_widgetMap.contains(message.hwnd)) return false;
     
     //get the real widget
     widget = m_widgetMap[message.hwnd];

     QPixmap thumbnail = QPixmap::grabWidget(widget).scaled(size, Qt::KeepAspectRatio);

     //QPixmap::Alpha in case the image has transparent regions
     HBITMAP hbitmap = thumbnail.toWinHBITMAP(QPixmap::Alpha);

     DwmSetIconicThumbnail(id, hbitmap, 0);
     DeleteObject(hbitmap);
     return true;

case WM_DWMSENDICONICLIVEPREVIEWBITMAP:
     //check if this is message is addressed to one of our widgets
     if (!m_widgetMap.contains(message.hwnd)) return false;
     
     //we want to grap the main window and show as a live preview
     widget = parent;

     QPixmap thumbnail = QPixmap::grabWidget(widget).scaled(size, Qt::KeepAspectRatio);

     HBITMAP hbitmap = thumbnail.toWinHBITMAP(QPixmap::NoAlpha);

     DwmSetIconicLivePreviewBitmap(id, hbitmap, 0);
     DeleteObject(hbitmap);
     return true;

case WM_ACTIVATE :
     if (LOWORD(message->wParam) == WA_ACTIVE) {
        //check if this is message is addressed to one of our widgets
        if (!m_widgetMap.contains(message->hwnd)) return false;
   
         //get the real widget
         widget = m_widgetMap[message->hwnd];
         
         //announce that widget was activated
         //..
     }
     //route message further
     return false;

case WM_CLOSE :
      //The same as for WM_ACTIVE except ..
      //announce that widget is about to be removed
      //..
      
      return false;


Updating the tab

When the content of the tab has changed, the thumbnail bitmap will not change by itself. That is why is needed to call DwmInvalidateIconicBitmaps. This will update the taskbar thumbnail for the specified tab.


The source code can be downloaded from here.

Strix Code Blog: Windows 7 or Vista UAC Shield Icon in Qt

Strix Code Blog: Windows 7 or Vista UAC Shield Icon in Qt: "(For a way to embed an application manifest with QtCreator see here) In a Qt application you cannot use the BCM_SETSHIELD message to show t..."

Thursday, March 24, 2011

Windows 7 Taskbar Extensions in Qt: Window Thumbnail Image

In this tutorial I'll explain how to set a iconic bitmap on a window to use as a thumbnail representation using Qt with MINGW.

Missing definitions and declarations

To be able to set a custom thumbnail, the following functions are required:
- DwmSetIconicThumbnail
- DwmSetWindowAttribute
- DwmSetIconicLivePreviewBitmap

These functions can be found in the Dwmapi.h header file. Unfortunately this file is not present in MINGW.

The solution is to call them directly from Dwmapi.dll.

Firstly it is needed to typedef a function pointer type to these functions.

extern "C"
{
    typedef HRESULT (WINAPI *t_DwmSetIconicThumbnail)(HWND hwnd, HBITMAP hbmp, DWORD dwSITFlags);
    typedef HRESULT (WINAPI *t_DwmSetWindowAttribute)(HWND hwnd, DWORD dwAttribute, LPCVOID pvAttribute, DWORD cbAttribute);
    typedef HRESULT (WINAPI *t_DwmSetIconicLivePreviewBitmap)(HWND hwnd, HBITMAP hbmp, POINT *pptClient, DWORD dwSITFlags);
}

Then, make wrappers which will call these functions directly from the dll.

void DwmSetIconicThumbnail(HWND hwnd, HBITMAP hbmp, DWORD dwSITFlags) {
    HMODULE shell;

    shell = LoadLibrary(L"dwmapi.dll");
    if (shell) {
        t_DwmSetIconicThumbnail set_iconic_thumbnail = reinterpret_cast<t_DwmSetIconicThumbnail>(GetProcAddress (shell, "DwmSetIconicThumbnail"));
        set_iconic_thumbnail(hwnd, hbmp, dwSITFlags);

        FreeLibrary (shell);
    }
}

void DwmSetWindowAttribute(HWND hwnd, DWORD dwAttribute, LPCVOID pvAttribute, DWORD cbAttribute) {
    HMODULE shell;

    shell = LoadLibrary(L"dwmapi.dll");
    if (shell) {
        t_DwmSetWindowAttribute set_window_attribute = reinterpret_cast<t_DwmSetWindowAttribute>(GetProcAddress (shell, "DwmSetWindowAttribute"));
        set_window_attribute(hwnd, dwAttribute, pvAttribute, cbAttribute);

        FreeLibrary (shell);
    }
}

void DwmSetIconicLivePreviewBitmap(HWND hwnd, HBITMAP hbmp, POINT *pptClient, DWORD dwSITFlags) {
    HMODULE shell;

    shell = LoadLibrary(L"dwmapi.dll");
    if (shell) {
        t_DwmSetIconicLivePreviewBitmap set_live_preview = reinterpret_cast<t_DwmSetIconicLivePreviewBitmap>(GetProcAddress (shell, "DwmSetIconicLivePreviewBitmap"));
        set_live_preview(hwnd, hbmp, pptClient, dwSITFlags);

        FreeLibrary (shell);
    }
}

Project settings

It is needed to add extra linkage libraries options to the linker.

LIBS += libgdi32


Setting the thumbnail

You need to do the following:
1) Call the DwmSetWindowAttribute function to set window attributes for non-client rendering to DWMWA_FORCE_ICONIC_REPRESENTATION and DWMWA_HAS_ICONIC_BITMAP
2) Catch WM_DWMSENDICONICTHUMBNAIL and WM_DWMSENDICONICLIVEPREVIEWBITMAP Windows events
3) Call DwmSetIconicThumbnail, on WM_DWMSENDICONICTHUMBNAIL event, to set thumbnail bitmap
4) Call DwmSetIconicLivePreviewBitmap, on DWMSENDICONICLIVEPREVIEWBITMAP event, to set the window live preview bitmap

Firslty, set window attributes:

void MainWindow::EnableIconicPreview(bool enable) {
    BOOL fForceIconic = enable ? TRUE : FALSE;
    BOOL fHasIconicBitmap = enable ? TRUE : FALSE;

    DwmSetWindowAttribute(
        this->winId(),
        DWMWA_FORCE_ICONIC_REPRESENTATION,
        &fForceIconic,
        sizeof(fForceIconic));


    DwmSetWindowAttribute(
        this->winId(),
        DWMWA_HAS_ICONIC_BITMAP,
        &fHasIconicBitmap,
        sizeof(fHasIconicBitmap));
}

Secondly, re-implement the QMainWindow winEvent protected function:
class MainWindow : public QMainWindow
{
//..

protected:
    bool winEvent(MSG * message, long * result);

//..
};

bool MainWindow::winEvent(MSG * message, long * result)
{
    switch (message->message)
    {
    case WM_DWMSENDICONICTHUMBNAIL:
        //call DwmSetIconicThumbnail
        break;

    case WM_DWMSENDICONICLIVEPREVIEWBITMAP:
        //call  DwmSetIconicLivePreviewBitmap
        break;
    default:
        return false;
    }

    return false;
}

On WM_DWMSENDICONICTHUMBNAIL event

Convert a QPixmap image to HBITMAP, and call DwmSetIconicThumbnail for this window:

QPixmap image(":/qtlogo.png");
HBITMAP hbitmap = m_image.toWinHBITMAP();
DwmSetIconicThumbnail(this->winId(), hbitmap, 0);
DeleteObject(hbitmap);



On WM_DWMSENDICONICLIVEPREVIEWBITMAP event

In this case it is required to provide the taskbar with a custom image of the selected window:

HBITMAP hbitmap = QPixmap::grabWidget(this).scaled(this->size(), Qt::KeepAspectRatio).toWinHBITMAP();
DwmSetIconicLivePreviewBitmap(this->winId(), hbitmap, 0, 0);

DeleteObject(hbitmap);

The result:

The code can be downloaded from here.

Useful link.

Windows 7 Taskbar Extensions in Qt: Thumbnail Toolbar

In this tutorial I'll explain how to create a Windows 7 thumbnail toolbar using Qt with MINGW GCC. At the end of the post you'll find the link to the project's code.

Missing definitions and declarations

MINGW GCC doesn't have all needed definitions and declarations to create a windows 7 thumbnail toolbar. That is why they need to be defined. I've explained how I did it in my previous post. You can browse the definitions file here.

Project settings

It is needed to add extra linkage libraries options to the linker.

LIBS += libcomctl32 libole32
Creating the thumbnail toolbar

In short you need to do the following:
1) Create an instance to the ITaskbarList3 COM interface
2) Create a list of images and add it to the thumbnail toolbar
3) Create a list of thumbnail toolbar buttons and add it to the toolbar
4) Update the buttons or the images when needed

What you can do:
1) Show/hide, disable/enable, change button details, update the image list
2) Have a thumbnail toolbar per program's window

What you can't do:
1) Add more than 7 buttons to the toolbar
2) Remove the toolbar (it will be destroyed when the window associated to it will be destroyed.)

Initialize the ITaskbarList3 COM interface

Firstly you need to implement your own winEvent function. This can be done by overriding the QMainWindow's winEvent protected function.

class MainWindow : public QMainWindow
{
//...
protected:
     bool winEvent(MSG * message, long * result);
//...
};

In order to initialize the ITaskbarList3 COM interface it is needed to register the
"TaskbarButtonCreated" event.

//..
unsigned int messageId = RegisterWindowMessage(L"TaskbarButtonCreated");
//..

When the event is registered, it is possible to obtain access to ITaskbarList3.

Putting all together:
//...
bool MainWindow::winEvent(MSG * message, long * result)
{
    static UINT taskBarCreatedId = WM_NULL;
    if (taskBarCreatedId == WM_NULL) {
        taskBarCreatedId = RegisterWindowMessage(L"TaskbarButtonCreated");
    }

    if (message->message == taskBarCreatedId) {
        //initialize the ITaskbarList3 interface
    } 

    return false;
}

Initializing the Interface

//..
void MainWindow::W7ToolbarInit() {
    HRESULT hr = CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_INPROC_SERVER, IID_ITaskbarList3,
                                  reinterpret_cast<void**> (&(m_w7toolbar)));

    if (SUCCEEDED(hr)){

        hr = m_w7toolbar->HrInit();

        if (FAILED(hr)) {
            m_w7toolbar->Release();
            m_w7toolbar = NULL;
        }
    }
}
//..

Create the list of images

The images I used in the project were PNG files 20x20 pixels, 32 bit, with transparency.

Create the image list to hold 4 images:

HIMAGELIST himl = ImageList_Create(20, 20, ILC_COLOR32, 4, 0);


Add the images to the list:
QPixmap img;
QBitmap mask;

img = QIcon(":/back.png").pixmap(20);
mask  = img.createMaskFromColor(Qt::transparent);
ImageList_Add(himl, img.toWinHBITMAP(QPixmap::PremultipliedAlpha), mask.toWinHBITMAP());

//repeat the same thing for the rest of the images

Set the thumbnailtoolbar's image list to the :
m_w7toolbar->ThumbBarSetImageList(this->winId(), himl);
"this" is a pointer to a QMainWindow object, but it also can be a QWidget pointer.

Free the allocated memory:
ImageList_Destroy(himl);

Add the buttons

Each button structure holds information about the button. Such as image index, the index from the image list, tool tip text, state, visibility and other flags.

It is important to remember, the thumbnail toolbar can't hold more than 7 buttons.

Let's say we want to have three buttons:
class MainWindow : public QMainWindow
{
//..
     THUMBBUTTON m_thbButtons[3];
//..
};

Initializing and adding the buttons:
#define IDTB_FIRST 3000

void MainWindow::W7ToolbarButtonsInit() {
    QString tooltips[3] = {"Prev", "Play", "Next"};

    for (int index = 0; index < 3; index++) {
        wcscpy(m_thbButtons[index].szTip, tooltips[index].toStdWString().c_str());

        //the ID of the button
        m_thbButtons[index].iId = IDTB_FIRST + index;
        //the image of the button, index from the image list
        m_thbButtons[index].iBitmap = index;
        
        //show tooltip and use the bitmpap index
        m_thbButtons[index].dwMask = (THUMBBUTTONMASK)(THB_BITMAP | THB_FLAGS | THB_TOOLTIP);

        //set the button enabled
        m_thbButtons[index].dwFlags = (THUMBBUTTONFLAGS)(THBF_ENABLED);

    }

    //set the buttons
    m_w7toolbar->ThumbBarAddButtons(this->winId(), 3, m_thbButtons);
}

Once the buttons are added, they should be visible.

Catching the thumbnailtoolbar click events

When a button is pressed, an event with the button's id is generated. These events can be caught in the winEvent function.

//...
bool MainWindow::winEvent(MSG * message, long * result)
{
    static UINT taskBarCreatedId = WM_NULL;
    if (taskBarCreatedId == WM_NULL) {
        taskBarCreatedId = RegisterWindowMessage(L"TaskbarButtonCreated");
    }

    if (message->message == taskBarCreatedId) {
        W7ToolbarInit();
        W7ToolbarSetImages();
        W7ToolbarButtonsInit();

    } else switch (message->message){
    case WM_COMMAND:
        {
            //get the button index
            int buttonId = LOWORD(message->wParam) - IDTB_FIRST;

            if ((buttonId >= 0) && (buttonId < 3)) {

                qDebug() << "Button " << buttonId << " was pressed";
                if (buttonId == 1) { //if "Play|Pause" was pressed

                    if (m_thbButtons[1].iBitmap == 1) {
                        //set the Pause image index
                        m_thbButtons[1].iBitmap = 3;
                        wcscpy(m_thbButtons[1].szTip, L"Pause");
                    } else {
                        //set the Play image index
                        m_thbButtons[1].iBitmap = 1;
                        wcscpy(m_thbButtons[1].szTip, L"Play");
                    }

                    //update the thumbnailtoolbar
                    m_w7toolbar->ThumbBarUpdateButtons(this->winId(), 3, m_thbButtons);
                }

            }


            break;
        }

    default:
        return false;

    }

    return false;
}

The code can be downloaded from here.
The screenshot can be seen below: