Assigning a file type to an Application on Windows

Background / technical stuff

File types in windows are defined in the Windows registry. First there is the entry of “<extension>” in HKCR which contains the file type name. In HKCR\<file type name> the different actions are defined.

This means, there is a file extension gidoc, whose files are called “MDI Text Editor Document”. These documents should be opened in an application, which is located here: E:\Developement\projects\debug\SimpleCryptIoDevided.exe. The file itself should be a parameter.

Using this pattern, each double click on a file opens a new Process which gets the file as parameter. This is fine for SDI (Single Document Interface) applications.

Example below:

  1. HKEY_CLASSES_ROOT
  2.     \.gidoc
  3.         "Default"="GiMdi.Document"
  4.     \ShellNew
  5.         "NullFile"=""
  6.  
  7.     \GiMdi.Document
  8.             "Default"="MDI Text Editor Document"
  9.         \DefaultIcon]
  10.             "Default"="E:\Developement\projects\debug\SimpleCryptIoDevided.exe,0"
  11.         \shell
  12.             \Open
  13.                 \command
  14.                     "Default"="E:\Developement\projects\debug\SimpleCryptIoDevided.exe  %1"

For MDI (Multi Document Interfaces), it should be opened in the existing Process. To achieve this, windows uses the old DDE mechanism. There must be some additional entries to achieve this:

  1. HKEY_CLASSES_ROOT
  2.     \GiMdi.Document
  3.         \shell
  4.             \Open
  5.                 \ddeexec
  6.                     "Default"="[open(\"%1\")]"
  7.                     \application]
  8.                         "Default"="SimpleCryptIoDevided"
  9.                     \topic
  10.                         "Default"="system"

If this is also added, Windows starts the process, which is given in command and then sends a WM_DDE_INITIATE broadcast message to windows. The application must react on this, then handle WM_DDE_EXECUTE messages and, if requested, WM_DDE_TERMINATE message. If the reaction on the DDE messages is not correc, Windows displays some error messages.

How to do it

Normally, your application registers the file types (changes the registry) during startup. If the DDE Mdi stuff should be used, it then has to create some ATOMS (::GlobalAddAtom). Then it starts up the rest and waits fo user input.

If the file type is registered, and no dde is set, the application is started with the file path as parameter.

If ddeexec keys are set in the registry, the application is started and the the DDE messages are send. While handling these messages, WM_DDE_ACK messages are send back to the caller and the messages must be handled.

This behaviour and the code would always look the same, only the registration keys and the handling of the DDE commands differ from application to application. There fore I created a class, that does all this and can be used as base class instead of QMainWindow: DocumentWindow.

Use the DocumentWindow class

If you want to create an (MDI) editor application, you can derive your main window class from DocumentWindow instead of QMainWindow. If you implement an MDI application, you should also reimplement the virtual method ddeOpenFile.
The example code is based on the Qt MDI Example [doc.qt.nokia.com]

  1. class MainWindow : public DocumentWindow
  2. {
  3. ...
  4. protected:
  5.     virtual void ddeOpenFile(const QString& filePath);
  6. }

all other things that need to be done is extending your constructor

  1. MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags flags) :
  2.     DocumentWindow(parent, flags)
  3. {
  4.     ...
  5.     registerFileType("GiMdi.Document",          // Document type name
  6.                      "MDI Text Editor Document",// User readable file type name
  7.                      ".gidoc",                  // file extension
  8.                      0,                         // index of the icon to use for the files.
  9.                      true);                     // register for DDE events
  10.     enableShellOpen();
  11.     ...
  12. }
  13. @endcode

and reimplement ddeFileOpen

  1. void MainWindow::ddeOpenFile(const QString& filePath)
  2. {
  3.     MdiChild *child = createMdiChild();
  4.     if (child->loadFile(filePath))
  5.     {
  6.         statusBar()->showMessage(tr("File loaded"), 2000);
  7.         child->show();
  8.     }
  9.     else
  10.     {
  11.         child->close();
  12.     }
  13. }

That’s it. Now it should work to just start the application, and the file type “.gidoc” is registered with your application. If you double click on it in the Windows explorer, it should be opened in the currently running Process or, if no instance of your application is running, start a new one. If your application has a windows icon in the resource (not in the qrc file! a windows resource file <file>.rc), this icon should be used for the files.

Use the DocumentWindow sources

DocumentWindow.h

  1. // -------------------------------------------------------------------------------------------------
  2. /**
  3.  *  @file
  4.  *  @brief
  5.  *  @author Gerolf Reinwardt
  6.  *  @date   30. march 2011
  7.  *
  8.  *  Copyright (c) 2011, Gerolf Reinwardt. All rights reserved.
  9.  *
  10.  *  Simplified BSD License
  11.  *
  12.  *  Redistribution and use in source and binary forms, with or without modification, are
  13.  *  permitted provided that the following conditions are met:
  14.  *
  15.  *  1. Redistributions of source code must retain the above copyright notice, this list of
  16.  *     conditions and the following disclaimer.
  17.  *
  18.  *  2. Redistributions in binary form must reproduce the above copyright notice, this list
  19.  *     of conditions and the following disclaimer in the documentation and/or other materials
  20.  *     provided with the distribution.
  21.  *
  22.  *  THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND ANY EXPRESS OR IMPLIED
  23.  *  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  24.  *  FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
  25.  *  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  26.  *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  27.  *  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  28.  *  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  29.  *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  30.  *  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31.  *
  32.  *  The views and conclusions contained in the software and documentation are those of the
  33.  *  authors and should not be interpreted as representing official policies, either expressed
  34.  *  or implied, of Gerolf Reinwardt.
  35.  */
  36. // -------------------------------------------------------------------------------------------------
  37.  
  38. #ifndef WIDGET_H
  39. #define WIDGET_H
  40.  
  41. // ----- general includes --------------------------------------------------------------------------
  42. #include <windows.h>
  43. #include <QtGui/QMainWindow>
  44.  
  45. // ----- local includes ----------------------------------------------------------------------------
  46. // ----- pre defines -------------------------------------------------------------------------------
  47.  
  48. // ----- class definition --------------------------------------------------------------------------
  49. /**
  50.  *  @short This class implements a main window with the ability to register file types on MS Windows and
  51.  *         react on the corresponding DDE events to open / print the files in an Windows MDI typical manner.
  52.  *
  53.  *  The usage is fairly easy. Derive your own MainWindow class from DocumentWindow instead of QMainWindow.
  54.  *  Inside your constructor, call registerFileType and enableShellOpen. The axample is build on top of the
  55.  *  Qt MDI Example (http://doc.qt.nokia.com/4.7/mainwindows-mdi.html)
  56.  *
  57.  *  @code
  58.     MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags flags) :
  59.         DocumentWindow(parent, flags)
  60.     {
  61.         ...
  62.  
  63.         registerFileType("GiMdi.Document", "MDI Text Editor Document", ".gidoc", 0, true);
  64.         enableShellOpen();
  65.  
  66.         setWindowTitle(tr("MDI"));
  67.         setUnifiedTitleAndToolBarOnMac(true);
  68.     }
  69.     @endcode
  70.  *
  71.  *  Aditionally, the actions must be performed by overwriting one or more of:
  72.  *  @li ddeOpenFile
  73.  *  @li ddeNewFile
  74.  *  @li ddePrintFile
  75.  *  @li executeUnknownDdeCommand
  76.  *
  77.  *  @code
  78.     void MainWindow::ddeOpenFile(const QString& filePath)
  79.     {
  80.         MdiChild *child = createMdiChild();
  81.         if (child->loadFile(filePath))
  82.         {
  83.             statusBar()->showMessage(tr("File loaded"), 2000);
  84.             child->show();
  85.         }
  86.         else
  87.         {
  88.             child->close();
  89.         }
  90.     }
  91.     @endcode
  92.  *
  93.  */
  94. class DocumentWindow : public QMainWindow
  95. {
  96.     Q_OBJECT
  97. public:
  98.     // ----- enums ---------------------------------------------------------------------------------
  99.     /**
  100.      *  Known DDE command. These commands are typically used
  101.      */
  102.     enum DdeCommand {
  103.         DDEOpen     = 0x0001, /**< open a file via explorer */
  104.         DDENew      = 0x0002, /**< create a new file via explorer */
  105.         DDEPrint    = 0x0004, /**< print a file via explorer */
  106.     };
  107.     Q_DECLARE_FLAGS(DdeCommands, DdeCommand)
  108.  
  109.     // ----- construction --------------------------------------------------------------------------
  110.     /**
  111.      *  Constructor.
  112.      *
  113.      *  Creates a DocumentWindow with a given @arg parent and @arg flags.
  114.      */
  115.     explicit DocumentWindow(QWidget* parent = 0, Qt::WindowFlags flags = 0);
  116.  
  117.     /**
  118.      *  Destructor
  119.      */
  120.     ~DocumentWindow();
  121.  
  122.     // ----- operators -----------------------------------------------------------------------------
  123.     // ----- methods -------------------------------------------------------------------------------
  124.     // ----- accessors -----------------------------------------------------------------------------
  125.     // ----- members -------------------------------------------------------------------------------
  126.  
  127. protected:
  128.     // ----- events --------------------------------------------------------------------------------
  129.     /**
  130.      *  reimpl as DDE events come as windows events and are not translated by Qt.
  131.      */
  132.     virtual bool winEvent(MSG *message, long *result);
  133.  
  134.     // ----- helpers for the file registration -----------------------------------------------------
  135.     /**
  136.      *  virtual function that must be implemented by the derived class to react to the open command
  137.      *  from Windows.
  138.      *
  139.      *  @param filePath file that was selected in the explorer
  140.      */
  141.     virtual void ddeOpenFile(const QString& filePath);
  142.  
  143.     /**
  144.      *  virtual function that must be implemented by the derived class to react to the new command
  145.      *  from Windows.
  146.      *
  147.      *  @param filePath file that was selected in the explorer
  148.      */
  149.     virtual void ddeNewFile(const QString& filePath);
  150.  
  151.     /**
  152.      *  virtual function that must be implemented by the derived class to react to the print command
  153.      *  from Windows.
  154.      *
  155.      *  @param filePath file that was selected in the explorer
  156.      */
  157.     virtual void ddePrintFile(const QString& filePath);
  158.  
  159.     /**
  160.      *  virtual function that must be implemented by get custom dde commands from the explorer. If, e.g.
  161.      *  a printo or copy command should be available in explorer and they are registered via registerCommand,
  162.      *  this function is called.
  163.      *
  164.      *  @param command  name of the command
  165.      *  @param params   parameter string, containing the hole stuff, also " and commas.
  166.      *
  167.      *  @note a command like this [compare("%1")] will result in the parameters:
  168.               command   = "compare";
  169.               params    = "\"<filepath>\"";
  170.      */
  171.     virtual void executeUnknownDdeCommand(const QString& command, const QString& params);
  172.  
  173.     /**
  174.      *  Call this method to register the file type in Windows. It creates the default command
  175.      *  which means the app is started with the file to open as parameter. If @arg registerForDDE
  176.      *  is true, the dde events are also created so the opening of a file is done in typical MDI
  177.      *  behavior (all files open in the same app).
  178.      *
  179.      *  @param documentId       id of the document, typically <Application>.Document --> see in registry, e.g. "GiMdi.Document"
  180.      *  @param fileTypeName     free name of the file type, e.g. "MDI Text Editor Document"
  181.      *  @param fileExtension    File extension, including the dot (e.g. ".gidoc")
  182.      *  @param appIconIndex     index of the app icon to use for the file in the windows explorer, typically the application icon
  183.      *  @param registerForDDE   true if DDE should be used (typical for MDI apps), typically false for SDI apps.
  184.      *  @param commands         a combination of the commands to install.
  185.      *
  186.      *  @note If more then the default commands are needed, then subsequent calls of registerCommand are needed.
  187.      *
  188.      *  @note DDEOpen  leads to the DDE command: [open("%1)]
  189.               DDENew   leads to the DDE command: [new("%1)]
  190.               DDEPrint leads to the DDE command: [print("%1)]
  191.      */
  192.     void registerFileType(const QString& documentId,
  193.                           const QString& fileTypeName,
  194.                           const QString& fileExtension,
  195.                           qint32         appIconIndex = 0,
  196.                           bool           registerForDDE = false,
  197.                           DdeCommands    commands = DDEOpen);
  198.  
  199.     /**
  200.      *  registeres one command for a given file type. It is called for the pre defined DDE command
  201.      *  types from registerFileType. if more then the normal commands are needed, it can be called
  202.      *  in addition to registerFileType.
  203.      *
  204.      *  @code
  205.         MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags flags) :
  206.             DocumentWindow(parent, flags)
  207.         {
  208.             ...
  209.  
  210.             registerFileType("GiMdi.Document", "MDI Text Editor Document", ".gidoc", 0, true);
  211.             registerCommand("fancyCommand", "GiMdi.Document", "-fancy %1", "[fancy(\"%1\")]");
  212.             enableShellOpen();
  213.  
  214.             ...
  215.         }
  216.         @endcode
  217.      */
  218.     void registerCommand(const QString& command,
  219.                          const QString& documentId,
  220.                          const QString cmdLineArg = QString::null,
  221.                          const QString ddeCommand = QString::null);
  222.  
  223.     /**
  224.      *  Call this method to enable the user to open data files associated with your application
  225.      *  by double-clicking the files in the windows file manager.
  226.      *
  227.      *  Use it together with registerFileType to register the fspezified file types or provida a
  228.      *  registry file (*.reg) which does this.
  229.      */
  230.     void enableShellOpen();
  231.  
  232.  
  233. private:
  234.     // ----- privat helpers ------------------------------------------------------------------------
  235.     /**
  236.      *  implementation of the WM_DDE_INITIATE windows message
  237.      */
  238.     bool ddeInitiate(MSG* message, long* result);
  239.  
  240.     /**
  241.      *  implementation of the WM_DDE_EXECUTE windows message
  242.      */
  243.     bool ddeExecute(MSG* message, long* result);
  244.  
  245.     /**
  246.      *  implementation of the WM_DDE_TERMINATE windows message
  247.      */
  248.     bool ddeTerminate(MSG* message, long* result);
  249.  
  250.     /**
  251.      *  Sets specified value in the registry under HKCU\Software\Classes, which is mapped to HKCR then.
  252.      */
  253.     bool SetHkcrUserRegKey(QString key, const QString& value, const QString& valueName = QString::null);
  254.  
  255.     /**
  256.      *  this method is called to do the DDE command handling. It does argument splitting and then calls
  257.      *  ddeOpenFile, ddeNewFile, ddePrintFile or executeUnknownDdeCommand.
  258.      */
  259.     void executeDdeCommand(const QString& command, const QString& params);
  260.  
  261.     // ----- members -------------------------------------------------------------------------------
  262.     bool    m_registerForDDE;       /**< used to identfy, if the dde commands should be written to the registry */
  263.     QString m_appAtomName;          /**< the name of the application, without file extension */
  264.     QString m_systemTopicAtomName;  /**< the name of the system topic atom, typically "System" */
  265.     ATOM    m_appAtom;              /**< The windows atom needed for DDE communication */
  266.     ATOM    m_systemTopicAtom;      /**< The windows system topic atom needed for DDE communication */
  267.     // ----- not allowed members -------------------------------------------------------------------
  268. };
  269.  
  270. Q_DECLARE_OPERATORS_FOR_FLAGS(DocumentWindow::DdeCommands)
  271.  
  272. #endif // WIDGET_H

DocumentWindow.cpp

  1. // -------------------------------------------------------------------------------------------------
  2. /**
  3.  *  @file
  4.  *  @brief
  5.  *  @author Gerolf Reinwardt
  6.  *  @date   30.01.2011
  7.  *
  8.  *  Copyright (c) 2011, Gerolf Reinwardt. All rights reserved.
  9.  *
  10.  *  Simplified BSD License
  11.  *
  12.  *  Redistribution and use in source and binary forms, with or without modification, are
  13.  *  permitted provided that the following conditions are met:
  14.  *
  15.  *  1. Redistributions of source code must retain the above copyright notice, this list of
  16.  *     conditions and the following disclaimer.
  17.  *
  18.  *  2. Redistributions in binary form must reproduce the above copyright notice, this list
  19.  *     of conditions and the following disclaimer in the documentation and/or other materials
  20.  *     provided with the distribution.
  21.  *
  22.  *  THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND ANY EXPRESS OR IMPLIED
  23.  *  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  24.  *  FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
  25.  *  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  26.  *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  27.  *  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  28.  *  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  29.  *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  30.  *  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31.  *
  32.  *  The views and conclusions contained in the software and documentation are those of the
  33.  *  authors and should not be interpreted as representing official policies, either expressed
  34.  *  or implied, of Gerolf Reinwardt.
  35.  */
  36. // -------------------------------------------------------------------------------------------------
  37.  
  38. // ----- general includes --------------------------------------------------------------------------
  39. #include <windows.h>
  40. #include <QtGui/QMessageBox>
  41. #include <QtGui/QApplication>
  42. #include <QtCore/QDir>
  43. #include <QtCore/QFileInfo>
  44. #include <QtCore/QRegExp>
  45.  
  46. // ----- local includes ----------------------------------------------------------------------------
  47. #include "documentwindow.h"
  48.  
  49.  
  50. // ----- construction ------------------------------------------------------------------------------
  51. DocumentWindow::DocumentWindow(QWidget* parent, Qt::WindowFlags flags) :
  52.     QMainWindow(parent, flags),
  53.     m_registerForDDE(false),
  54.     m_appAtomName(),
  55.     m_systemTopicAtomName("system"),
  56.     m_appAtom(0),
  57.     m_systemTopicAtom(0)
  58. {
  59.     QFileInfo fi(qApp->applicationFilePath());
  60.     m_appAtomName = fi.baseName();
  61. }
  62.  
  63. DocumentWindow::~DocumentWindow()
  64. {
  65.     if(0 != m_appAtom)
  66.     {
  67.         ::GlobalDeleteAtom(m_appAtom);
  68.         m_appAtom = 0;
  69.     }
  70.     if(0 != m_systemTopicAtom)
  71.     {
  72.         ::GlobalDeleteAtom(m_systemTopicAtom);
  73.         m_systemTopicAtom = 0;
  74.     }
  75. }
  76.  
  77. // ----- operators ---------------------------------------------------------------------------------
  78. // ----- methods -----------------------------------------------------------------------------------
  79. // ----- accessors ---------------------------------------------------------------------------------
  80. // ----- public slots ------------------------------------------------------------------------------
  81. // ----- protected slots ---------------------------------------------------------------------------
  82. // ----- events ------------------------------------------------------------------------------------
  83. bool DocumentWindow::winEvent(MSG *message, long *result)
  84. {
  85.     switch(message->message)
  86.     {
  87.     case WM_DDE_INITIATE:
  88.         return ddeInitiate(message, result);
  89.         break;
  90.     case WM_DDE_EXECUTE:
  91.         return ddeExecute(message, result);
  92.         break;
  93.     case WM_DDE_TERMINATE:
  94.         return ddeTerminate(message, result);
  95.         break;
  96.     }
  97.  
  98.     return QMainWindow::winEvent(message, result);
  99. }
  100.  
  101. void DocumentWindow::ddeOpenFile(const QString&&#41;
  102. {
  103.     // this method will be overwritten, if the application uses the dde open command
  104. }
  105.  
  106. void DocumentWindow::ddeNewFile(const QString&&#41;
  107. {
  108.     // this method will be overwritten, if the application uses the dde new command
  109. }
  110.  
  111. void DocumentWindow::ddePrintFile(const QString&&#41;
  112. {
  113.     // this method will be overwritten, if the application uses the dde print command
  114. }
  115.  
  116. void DocumentWindow::executeUnknownDdeCommand(const QString&, const QString&)
  117. {
  118.     // this method will be overwritten, if the application uses other commands,
  119.     // then open, new and print via DDE and Explorer
  120. }
  121.  
  122. void DocumentWindow::registerFileType(const QString& documentId,
  123.                                       const QString& fileTypeName,
  124.                                       const QString& fileExtension,
  125.                                       qint32         appIconIndex,
  126.                                       bool           registerForDDE,
  127.                                       DdeCommands    commands)
  128. {
  129.     // first register the type ID of our server
  130.     if (!SetHkcrUserRegKey(documentId, fileTypeName))
  131.         return;
  132.  
  133.     if (!SetHkcrUserRegKey(QString("%1\\DefaultIcon").arg(documentId),
  134.                    QString("\"%1\",%2").arg(QDir::toNativeSeparators(qApp->applicationFilePath())).arg(appIconIndex)))
  135.         return;
  136.  
  137.     m_registerForDDE = registerForDDE;
  138.  
  139.     if(commands & DDEOpen)
  140.         registerCommand("Open", documentId, "\"%1\"", "[open(\"%1\")]");
  141.     if(commands & DDENew)
  142.         registerCommand("New", documentId, "-new \"%1\"", "[new(\"%1\")]");
  143.     if(commands & DDEPrint)
  144.         registerCommand("Print", documentId, "-print \"%1\"", "[print(\"%1\")]");
  145.  
  146.     LONG lSize = _MAX_PATH * 2;
  147.     wchar_t szTempBuffer[_MAX_PATH * 2];
  148.     LONG lResult = ::RegQueryValue(HKEY_CLASSES_ROOT,
  149.                                    (const wchar_t*)fileExtension.utf16(),
  150.                                    szTempBuffer,
  151.                                    &lSize);
  152.  
  153.     QString temp = QString::fromUtf16((unsigned short*)szTempBuffer);
  154.  
  155.     if (lResult != ERROR_SUCCESS || temp.isEmpty() || temp == documentId)
  156.     {
  157.         // no association for that suffix
  158.         if (!SetHkcrUserRegKey(fileExtension, documentId))
  159.             return;
  160.  
  161.         SetHkcrUserRegKey(QString("%1\\ShellNew").arg(fileExtension), QLatin1String(""), QLatin1String("NullFile"));
  162.     }
  163. }
  164.  
  165. void DocumentWindow::registerCommand(const QString& command,
  166.                                      const QString& documentId,
  167.                                      const QString cmdLineArg,
  168.                                      const QString ddeCommand)
  169. {
  170.     QString commandLine = QDir::toNativeSeparators(qApp->applicationFilePath());
  171.     commandLine.prepend(QLatin1String("\""));
  172.     commandLine.append(QLatin1String("\""));
  173.  
  174.     if(!cmdLineArg.isEmpty())
  175.     {
  176.         commandLine.append(QChar(' '));
  177.         commandLine.append(cmdLineArg);
  178.     }
  179.  
  180.     if (!SetHkcrUserRegKey(QString("%1\\shell\\%2\\command").arg(documentId).arg(command), commandLine))
  181.         return;       // just skip it
  182.  
  183.     if(m_registerForDDE)
  184.     {
  185.         if (!SetHkcrUserRegKey(QString("%1\\shell\\%2\\ddeexec").arg(documentId).arg(command), ddeCommand))
  186.             return;
  187.  
  188.         if (!SetHkcrUserRegKey(QString("%1\\shell\\%2\\ddeexec\\application").arg(documentId).arg(command), m_appAtomName))
  189.             return;
  190.  
  191.         if (!SetHkcrUserRegKey(QString("%1\\shell\\%2\\ddeexec\\topic").arg(documentId).arg(command), m_systemTopicAtomName))
  192.             return;
  193.     }
  194. }
  195.  
  196. void DocumentWindow::enableShellOpen()
  197. {
  198.     if((0 != m_appAtom) || (0 != m_systemTopicAtom))
  199.         return;
  200.  
  201.     m_appAtom = ::GlobalAddAtomW((const wchar_t*)m_appAtomName.utf16());
  202.     m_systemTopicAtom = ::GlobalAddAtomW((const wchar_t*)m_systemTopicAtomName.utf16());
  203. }
  204.  
  205. // ----- private slots -----------------------------------------------------------------------------
  206. // ----- private helpers ---------------------------------------------------------------------------
  207. bool DocumentWindow::ddeInitiate(MSG* message, long* result)
  208. {
  209.     if( (0 != LOWORD(message->lParam)) &&
  210.         (0 != HIWORD(message->lParam)) &&
  211.         (LOWORD(message->lParam) == m_appAtom) &&
  212.         (HIWORD(message->lParam) == m_systemTopicAtom))
  213.     {
  214.         // make duplicates of the incoming atoms (really adding a reference)
  215.         wchar_t atomName[_MAX_PATH];
  216.         Q_ASSERT(::GlobalGetAtomNameW(m_appAtom, atomName, _MAX_PATH - 1) != 0);
  217.         Q_ASSERT(::GlobalAddAtomW(atomName) == m_appAtom);
  218.         Q_ASSERT(::GlobalGetAtomNameW(m_systemTopicAtom, atomName, _MAX_PATH - 1) != 0);
  219.         Q_ASSERT(::GlobalAddAtomW(atomName) == m_systemTopicAtom);
  220.  
  221.         // send the WM_DDE_ACK (caller will delete duplicate atoms)
  222.         ::SendMessage((HWND)message->wParam, WM_DDE_ACK, (WPARAM)winId(), MAKELPARAM(m_appAtom, m_systemTopicAtom));
  223.     }
  224.     *result = 0;
  225.     return true;
  226. }
  227.  
  228. bool DocumentWindow::ddeExecute(MSG* message, long* result)
  229. {
  230.     // unpack the DDE message
  231.     UINT_PTR unused;
  232.     HGLOBAL hData;
  233.     //IA64: Assume DDE LPARAMs are still 32-bit
  234.     Q_ASSERT(::UnpackDDElParam(WM_DDE_EXECUTE, message->lParam, &unused, (UINT_PTR*)&hData));
  235.  
  236.     QString command = QString::fromWCharArray((LPCWSTR)::GlobalLock(hData));
  237.     ::GlobalUnlock(hData);
  238.  
  239.     // acknowledge now - before attempting to execute
  240.     ::PostMessage((HWND)message->wParam, WM_DDE_ACK, (WPARAM)winId(),
  241.                   //IA64: Assume DDE LPARAMs are still 32-bit
  242.                   ReuseDDElParam(message->lParam, WM_DDE_EXECUTE, WM_DDE_ACK, (UINT)0x8000, (UINT_PTR)hData));
  243.  
  244.     // don't execute the command when the window is disabled
  245.     if (!isEnabled())
  246.     {
  247.         *result = 0;
  248.         return true;
  249.     }
  250.  
  251.     QRegExp regCommand("^\\[(\\w+)\\((.*)\\)\\]$");
  252.     if(regCommand.exactMatch(command))
  253.     {
  254.         executeDdeCommand(regCommand.cap(1), regCommand.cap(2));
  255.     }
  256.  
  257.     *result = 0;
  258.     return true;
  259. }
  260.  
  261. bool DocumentWindow::ddeTerminate(MSG* message, long* result)
  262. {
  263.     // The client or server application should respond by posting a WM_DDE_TERMINATE message.
  264.     ::PostMessageW((HWND)message->wParam, WM_DDE_TERMINATE, (WPARAM)winId(), message->lParam);
  265.     return true;
  266. }
  267.  
  268. bool DocumentWindow::SetHkcrUserRegKey(QString key, const QString& value, const QString& valueName)
  269. {
  270.     HKEY hKey;
  271.  
  272.     key.prepend("Software\\Classes\\");
  273.  
  274.     LONG lRetVal = RegCreateKey(HKEY_CURRENT_USER,
  275.                                 (const wchar_t*)key.utf16(),
  276.                                 &hKey);
  277.  
  278.     if(ERROR_SUCCESS == lRetVal)
  279.     {
  280.         LONG lResult = ::RegSetValueExW(hKey,
  281.                                        valueName.isEmpty() ? 0 : (const wchar_t*)valueName.utf16(),
  282.                                        0,
  283.                                        REG_SZ,
  284.                                        (CONST BYTE*)value.utf16(),
  285.                                        (value.length() + 1) * sizeof(wchar_t));
  286.  
  287.         if(::RegCloseKey(hKey) == ERROR_SUCCESS && lResult == ERROR_SUCCESS)
  288.             return true;
  289.  
  290.         QMessageBox::warning(0, QString("Error in setting Registry values"),
  291.                              QString("registration database update failed for key '%s'.").arg(key));
  292.     }
  293.     else
  294.     {
  295.         wchar_t buffer[4096];
  296.         ::FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, 0, lRetVal, 0, buffer, 4096, 0);
  297.         QString szText = QString::fromUtf16((const ushort*)buffer);
  298.         QMessageBox::warning(this, QString("Error in setting Registry values"), szText);
  299.     }
  300.     return false;
  301. }
  302.  
  303. void DocumentWindow::executeDdeCommand(const QString& command, const QString& params)
  304. {
  305.     QRegExp regCommand("^\"(.*)\"$");
  306.     bool singleCommand = regCommand.exactMatch(params);
  307.     if((0 == command.compare("open", Qt::CaseInsensitive)) && singleCommand)
  308.     {
  309.         ddeOpenFile(regCommand.cap(1));
  310.     }
  311.     else if((0 == command.compare("new", Qt::CaseInsensitive)) && singleCommand)
  312.     {
  313.         ddeNewFile(regCommand.cap(1));
  314.     }
  315.     else if((0 == command.compare("print", Qt::CaseInsensitive)) && singleCommand)
  316.     {
  317.         ddePrintFile(regCommand.cap(1));
  318.     }
  319.     else
  320.     {
  321.         executeUnknownDdeCommand(command, params);
  322.     }
  323. }

You may use this code without any warranty.

Future extensions

The class might be extended so it also works on Linux or Mac. The code of the class and a demo project are located on gitorious in the following repository: qtdevnet-registereditorfiletype [gitorious.org]

Versions

The current code is version 1 of the code.

Version 1

This marks the first public release.

Feedback

I would really welcome feedback on this class. If you spot big weaknesses, please let me know. For discussion on this wiki, please use this forum thread [developer.qt.nokia.com] .

Categories: