Assigning a file type to an Application on Windows: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
Line 3: Line 3:
'''English''' | [[Assigning_a_file_type_to_an_Application_on_Windows_German|Deutsch]]
'''English''' | [[Assigning_a_file_type_to_an_Application_on_Windows_German|Deutsch]]


[toc align_right="yes" depth="3"]
[toc align_right="yes" depth="3"]


= Assigning a file type to an Application on Windows =
= Assigning a file type to an Application on Windows =
Line 9: Line 9:
== Background / technical stuff ==
== 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 HKCRamp;lt;file type name> the different actions are defined.
File types in windows are defined in the Windows registry. First there is the entry of "<extension&amp;amp;gt;" in HKCR which contains the file type name. In HKCRamp;lt;file type name&amp;amp;gt; the different actions are defined.


This means, there is a file extension '''gidoc''', whose files are called &quot;MDI Text Editor Document&amp;quot;. These documents should be opened in an application, which is located here: E:.exe. The file itself should be a parameter.
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:.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.
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.
Line 17: Line 17:
Example below:
Example below:


<code><br />HKEY_CLASSES_ROOT<br /> idoc<br /> &quot;Default&amp;quot;=&quot;GiMdi.Document&amp;quot;<br /> &quot;NullFile&amp;quot;=&quot;&quot;
<code>
HKEY_CLASSES_ROOT
idoc
"Default"="GiMdi.Document"
"NullFile"=""


.Document<br /> &quot;Default&amp;quot;=&quot;MDI Text Editor Document&amp;quot;<br /> ]<br /> &quot;Default&amp;quot;=&quot;E:.exe,0&amp;quot;<br /> &quot;Default&amp;quot;=&quot;E:.exe %1&amp;quot;<br /></code>
.Document
"Default"="MDI Text Editor Document"
]
"Default"="E:.exe,0"
"Default"="E:.exe %1"
</code>


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:
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:


<code><br />HKEY_CLASSES_ROOT<br /> .Document<br /> &quot;Default&amp;quot;=&quot;[open(quot;%1quot;)]&quot;<br /> ]<br /> &quot;Default&amp;quot;=&quot;SimpleCryptIoDevided&amp;quot;<br /> &quot;Default&amp;quot;=&quot;system&amp;quot;<br /></code>
<code>
HKEY_CLASSES_ROOT
.Document
"Default"="[open(quot;%1quot;)]"
]
"Default"="SimpleCryptIoDevided"
"Default"="system"
</code>


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.
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.
Line 39: Line 55:
== Use the DocumentWindow class ==
== 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 &lt;code&amp;gt;ddeOpenFile&amp;lt;/code&amp;gt;.<br />The example code is based on the &quot;Qt MDI Example&amp;quot;:http://doc.qt.nokia.com/4.7/mainwindows-mdi.html
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 <code>ddeOpenFile</code>.
The example code is based on the "Qt MDI Example":http://doc.qt.nokia.com/4.7/mainwindows-mdi.html


<code><br />class MainWindow : public DocumentWindow<br />{<br /><br />protected:<br /> virtual void ddeOpenFile&amp;amp;#40;const QString&amp;amp; filePath&amp;amp;#41;;<br />}<br /></code>
<code>
class MainWindow : public DocumentWindow
{
protected:
virtual void ddeOpenFile(const QString&amp;amp; filePath);
}
</code>


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


<code><br />MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags flags) :<br /> DocumentWindow(parent, flags)<br />{<br /> <br /> registerFileType(&quot;GiMdi.Document&amp;quot;, // Document type name<br /> &quot;MDI Text Editor Document&amp;quot;,// User readable file type name<br /> &quot;.gidoc&amp;quot;, // file extension<br /> 0, // index of the icon to use for the files.<br /> true); // register for DDE events<br /> enableShellOpen();<br /> <br />}<br /></code>endcode<br /><code>
<code>
MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags flags) :
DocumentWindow(parent, flags)
{
registerFileType("GiMdi.Document", // Document type name
"MDI Text Editor Document",// User readable file type name
".gidoc", // file extension
0, // index of the icon to use for the files.
true); // register for DDE events
enableShellOpen();
}
</code>endcode
<code>


and reimplement ddeFileOpen
and reimplement ddeFileOpen


</code><br />void MainWindow::ddeOpenFile&amp;amp;#40;const QString&amp;amp; filePath&amp;amp;#41;<br />{<br /> MdiChild '''child = createMdiChild();<br /> if (child-&gt;loadFile&amp;amp;#40;filePath&amp;amp;#41;)<br /> {<br /> statusBar()<s>&gt;showMessage(tr(&quot;File loaded&amp;quot;), 2000);<br /> child</s>&gt;show();<br /> }<br /> else<br /> {<br /> child-&gt;close();<br /> }<br />}<br /><code>
</code>
<br />That's it. Now it should work to just start the application, and the file type &quot;.gidoc&amp;quot; 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 &lt;file&amp;gt;.rc), this icon should be used for the files.
void MainWindow::ddeOpenFile(const QString&amp;amp; filePath)
<br />h2. Use the DocumentWindow sources
{
<br />h3. DocumentWindow.h
MdiChild '''child = createMdiChild();
<br /></code><br />// ————————————————————————————————-<br />/'''*<br /> * <code>file<br /> * </code>brief<br /> * <code>author Gerolf Reinwardt<br /> * </code>date 30. march 2011<br /> *<br /> * Copyright © 2011, Gerolf Reinwardt. All rights reserved.<br /> *<br /> * Simplified BSD License<br /> *<br /> * Redistribution and use in source and binary forms, with or without modification, are<br /> * permitted provided that the following conditions are met:<br /> *<br /> * 1. Redistributions of source code must retain the above copyright notice, this list of<br /> * conditions and the following disclaimer.<br /> *<br /> * 2. Redistributions in binary form must reproduce the above copyright notice, this list<br /> * of conditions and the following disclaimer in the documentation and/or other materials<br /> * provided with the distribution.<br /> *<br /> * THIS SOFTWARE IS PROVIDED BY &lt;COPYRIGHT HOLDER&amp;gt; ``AS IS'' AND ANY EXPRESS OR IMPLIED<br /> * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND<br /> * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL &lt;COPYRIGHT HOLDER&amp;gt; OR<br /> * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR<br /> * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR<br /> * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON<br /> * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING<br /> * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF<br /> * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.<br /> *<br /> * The views and conclusions contained in the software and documentation are those of the<br /> * authors and should not be interpreted as representing official policies, either expressed<br /> * or implied, of Gerolf Reinwardt.<br /> '''/<br />// ————————————————————————————————-
if (child->loadFile(filePath))
<br />#ifndef WIDGET_H<br />#define WIDGET_H
{
<br />// —— general includes —————————————————————————<br />#include &lt;windows.h&amp;gt;<br />#include &lt;QtGui/QMainWindow&amp;gt;
statusBar()->showMessage(tr("File loaded"), 2000);
<br />// —— local includes —————————————————————————-<br />// —— pre defines ——————————————————————————-
child->show();
<br />// —— class definition —————————————————————————<br />/'''*<br /> * <code>short This class implements a main window with the ability to register file types on MS Windows and<br /> * react on the corresponding DDE events to open / print the files in an Windows MDI typical manner.<br /> *<br /> * The usage is fairly easy. Derive your own MainWindow class from DocumentWindow instead of QMainWindow.<br /> * Inside your constructor, call registerFileType and enableShellOpen. The axample is build on top of the<br /> * Qt MDI Example (http://doc.qt.nokia.com/4.7/mainwindows-mdi.html)<br /> *<br /> * </code>code<br /> MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags flags) :<br /> DocumentWindow(parent, flags)<br /> {<br />
}
else
{
child->close();
}
}
<code>


registerFileType(&quot;GiMdi.Document&amp;quot;, &quot;MDI Text Editor Document&amp;quot;, &quot;.gidoc&amp;quot;, 0, true);<br /> enableShellOpen();
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.


setWindowTitle(tr(&quot;MDI&amp;quot;));<br /> setUnifiedTitleAndToolBarOnMac(true);<br /> }<br /> <code>endcode<br /> *<br /> * Aditionally, the actions must be performed by overwriting one or more of:<br /> * </code>li ddeOpenFile<br /> * <code>li ddeNewFile<br /> * </code>li ddePrintFile<br /> * <code>li executeUnknownDdeCommand<br /> *<br /> * </code>code<br /> void MainWindow::ddeOpenFile&amp;amp;#40;const QString&amp;amp; filePath&amp;amp;#41;<br /> {<br /> MdiChild '''child = createMdiChild();<br /> if (child-&gt;loadFile&amp;amp;#40;filePath&amp;amp;#41;)<br /> {<br /> statusBar()<s>&gt;showMessage(tr(&quot;File loaded&amp;quot;), 2000);<br /> child</s>&gt;show();<br /> }<br /> else<br /> {<br /> child-&gt;close();<br /> }<br /> }<br /> <code>endcode<br />'''<br /> '''/<br />class DocumentWindow : public QMainWindow<br />{<br /> Q_OBJECT<br />public:<br /> // —— enums ———————————————————————————<br /> /'''*<br /> * Known DDE command. These commands are typically used<br /> '''/<br /> enum DdeCommand {<br /> DDEOpen = 0x0001, /&lt; open a file via explorer'''/<br /> DDENew = 0x0002, /*'''&lt; create a new file via explorer'''/<br /> DDEPrint = 0x0004, /*'''&lt; print a file via explorer'''/<br /> };<br /> Q_DECLARE_FLAGS(DdeCommands, DdeCommand)
h2. Use the DocumentWindow sources


// —— construction —————————————————————————<br /> /**<br /> * Constructor.<br /> *<br /> * Creates a DocumentWindow with a given </code>arg parent and </code>arg flags.<br /> '''/<br /> explicit DocumentWindow(QWidget''' parent = 0, Qt::WindowFlags flags = 0);
h3. DocumentWindow.h


/**<br /> * Destructor<br /> '''/<br /> ~DocumentWindow();
</code>
<br /> // —— operators ——————————————————————————<br /> // —— methods ——————————————————————————-<br /> // —— accessors ——————————————————————————<br /> // —— members ——————————————————————————-
// ————————————————————————————————-
<br />protected:<br /> // —— events ———————————————————————————<br /> /'''*<br /> * reimpl as DDE events come as windows events and are not translated by Qt.<br /> */<br /> virtual bool winEvent(MSG *message, long '''result);
/'''*
<br /> // —— helpers for the file registration ——————————————————<br /> /'''*<br /> * virtual function that must be implemented by the derived class to react to the open command<br /> * from Windows.<br /> *<br /> * <code>param filePath file that was selected in the explorer<br /> '''/<br /> virtual void ddeOpenFile&amp;amp;#40;const QString&amp;amp; filePath&amp;amp;#41;;
* <code>file
<br /> /'''*<br /> * virtual function that must be implemented by the derived class to react to the new command<br /> * from Windows.<br /> *<br /> * </code>param filePath file that was selected in the explorer<br /> '''/<br /> virtual void ddeNewFile&amp;amp;#40;const QString&amp;amp; filePath&amp;amp;#41;;
* </code>brief
<br /> /'''*<br /> * virtual function that must be implemented by the derived class to react to the print command<br /> * from Windows.<br /> *<br /> * <code>param filePath file that was selected in the explorer<br /> '''/<br /> virtual void ddePrintFile&amp;amp;#40;const QString&amp;amp; filePath&amp;amp;#41;;
* <code>author Gerolf Reinwardt
<br /> /'''*<br /> * virtual function that must be implemented by get custom dde commands from the explorer. If, e.g.<br /> * a printo or copy command should be available in explorer and they are registered via registerCommand,<br /> * this function is called.<br /> *<br /> * </code>param command name of the command<br /> * <code>param params parameter string, containing the hole stuff, also &quot; and commas.<br /> *<br /> * </code>note a command like this [compare(&quot;%1&amp;quot;)] will result in the parameters:<br /> command = &quot;compare&amp;quot;;<br /> params = &quot;quot;&lt;filepath&amp;gt;quot;&quot;;<br /> '''/<br /> virtual void executeUnknownDdeCommand(const QString&amp;amp; command, const QString&amp;amp; params);
* </code>date 30. march 2011
<br /> /'''*<br /> * Call this method to register the file type in Windows. It creates the default command<br /> * which means the app is started with the file to open as parameter. If <code>arg registerForDDE<br /> * is true, the dde events are also created so the opening of a file is done in typical MDI<br /> * behavior (all files open in the same app).<br /> *<br /> * </code>param documentId id of the document, typically &lt;Application&amp;gt;.Document —&amp;gt; see in registry, e.g. &quot;GiMdi.Document&amp;quot;<br /> * <code>param fileTypeName free name of the file type, e.g. &quot;MDI Text Editor Document&amp;quot;<br /> * </code>param fileExtension File extension, including the dot (e.g. &quot;.gidoc&amp;quot;)<br /> * <code>param appIconIndex index of the app icon to use for the file in the windows explorer, typically the application icon<br /> * </code>param registerForDDE true if DDE should be used (typical for MDI apps), typically false for SDI apps.<br /> * <code>param commands a combination of the commands to install.<br /> *<br /> * </code>note If more then the default commands are needed, then subsequent calls of registerCommand are needed.<br /> *<br /> * <code>note DDEOpen leads to the DDE command: [open(&quot;%1)]<br /> DDENew leads to the DDE command: [new(&quot;%1)]<br /> DDEPrint leads to the DDE command: [print(&quot;%1)]<br /> '''/<br /> void registerFileType(const QString&amp;amp; documentId,<br /> const QString&amp;amp; fileTypeName,<br /> const QString&amp;amp; fileExtension,<br /> qint32 appIconIndex = 0,<br /> bool registerForDDE = false,<br /> DdeCommands commands = DDEOpen);
*
<br /> /'''*<br /> * registeres one command for a given file type. It is called for the pre defined DDE command<br /> * types from registerFileType. if more then the normal commands are needed, it can be called<br /> * in addition to registerFileType.<br /> *<br /> * </code>code<br /> MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags flags) :<br /> DocumentWindow(parent, flags)<br /> {<br /> …
* Copyright © 2011, Gerolf Reinwardt. All rights reserved.
*
* Simplified BSD License
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of Gerolf Reinwardt.
*/
// ————————————————————————————————-


registerFileType(&quot;GiMdi.Document&amp;quot;, &quot;MDI Text Editor Document&amp;quot;, &quot;.gidoc&amp;quot;, 0, true);<br /> registerCommand(&quot;fancyCommand&amp;quot;, &quot;GiMdi.Document&amp;quot;, &quot;<s>fancy %1&amp;quot;, &quot;[fancy(quot;%1quot;)]&quot;);<br /> enableShellOpen();
#ifndef WIDGET_H
<br /> …<br /> }<br /> <code>endcode<br /> '''/<br /> void registerCommand(const QString&amp;amp; command,<br /> const QString&amp;amp; documentId,<br /> const QString cmdLineArg = QString::null,<br /> const QString ddeCommand = QString::null);
#define WIDGET_H
<br /> /'''*<br /> * Call this method to enable the user to open data files associated with your application<br /> * by double-clicking the files in the windows file manager.<br /> *<br /> * Use it together with registerFileType to register the fspezified file types or provida a<br /> * registry file &amp;#40;'''.reg&amp;amp;#41; which does this.<br />'''/<br /> void enableShellOpen();


<br />private:<br /> // —— privat helpers ————————————————————————<br /> /**<br /> * implementation of the WM_DDE_INITIATE windows message<br /> '''/<br /> bool ddeInitiate(MSG''' message, long* result);
// —— general includes —————————————————————————
<br /> /**<br /> * implementation of the WM_DDE_EXECUTE windows message<br /> '''/<br /> bool ddeExecute(MSG''' message, long* result);
#include <windows.h>
<br /> /**<br /> * implementation of the WM_DDE_TERMINATE windows message<br /> '''/<br /> bool ddeTerminate(MSG''' message, long* result);
#include <QtGui/QMainWindow>
<br /> /**<br /> * Sets specified value in the registry under HKCU\Software\Classes, which is mapped to HKCR then.<br /> '''/<br /> bool SetHkcrUserRegKey(QString key, const QString&amp;amp; value, const QString&amp;amp; valueName = QString::null);
 
<br /> /'''*<br /> * this method is called to do the DDE command handling. It does argument splitting and then calls<br /> * ddeOpenFile, ddeNewFile, ddePrintFile or executeUnknownDdeCommand.<br /> '''/<br /> void executeDdeCommand(const QString&amp;amp; command, const QString&amp;amp; params);
// —— local includes —————————————————————————-
<br /> // —— members ——————————————————————————-<br /> bool m_registerForDDE; /&lt; used to identfy, if the dde commands should be written to the registry'''/<br /> QString m_appAtomName; /*'''&lt; the name of the application, without file extension'''/<br /> QString m_systemTopicAtomName; /*'''&lt; the name of the system topic atom, typically &quot;System&amp;quot;'''/<br /> ATOM m_appAtom; /*'''&lt; The windows atom needed for DDE communication'''/<br /> ATOM m_systemTopicAtom; /*'''&lt; The windows system topic atom needed for DDE communication'''/<br /> // —— not allowed members ——————————————————————</s><br />};
// —— pre defines ——————————————————————————-
 
// —— class definition —————————————————————————
/'''*
* <code>short This class implements a main window with the ability to register file types on MS Windows and
* react on the corresponding DDE events to open / print the files in an Windows MDI typical manner.
*
* The usage is fairly easy. Derive your own MainWindow class from DocumentWindow instead of QMainWindow.
* Inside your constructor, call registerFileType and enableShellOpen. The axample is build on top of the
* Qt MDI Example (http://doc.qt.nokia.com/4.7/mainwindows-mdi.html)
*
* </code>code
MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags flags) :
DocumentWindow(parent, flags)
{
 
registerFileType("GiMdi.Document", "MDI Text Editor Document", ".gidoc", 0, true);
enableShellOpen();
 
setWindowTitle(tr("MDI"));
setUnifiedTitleAndToolBarOnMac(true);
}
<code>endcode
*
* Aditionally, the actions must be performed by overwriting one or more of:
* </code>li ddeOpenFile
* <code>li ddeNewFile
* </code>li ddePrintFile
* <code>li executeUnknownDdeCommand
*
* </code>code
void MainWindow::ddeOpenFile(const QString&amp;amp; filePath)
{
MdiChild '''child = createMdiChild();
if (child->loadFile(filePath))
{
statusBar()->showMessage(tr("File loaded"), 2000);
child->show();
}
else
{
child->close();
}
}
<code>endcode
'''
*/
class DocumentWindow : public QMainWindow
{
Q_OBJECT
public:
// —— enums ———————————————————————————
/'''*
* Known DDE command. These commands are typically used
*/
enum DdeCommand {
DDEOpen = 0x0001, /< open a file via explorer*/
DDENew = 0x0002, /*'''< create a new file via explorer*/
DDEPrint = 0x0004, /*'''< print a file via explorer*/
};
Q_DECLARE_FLAGS(DdeCommands, DdeCommand)
 
// —— construction —————————————————————————
/**
* Constructor.
*
* Creates a DocumentWindow with a given </code>arg parent and </code>arg flags.
*/
explicit DocumentWindow(QWidget''' parent = 0, Qt::WindowFlags flags = 0);
 
/**
* Destructor
*/
~DocumentWindow();
 
// —— operators ——————————————————————————
// —— methods ——————————————————————————-
// —— accessors ——————————————————————————
// —— members ——————————————————————————-
 
protected:
// —— events ———————————————————————————
/'''*
* reimpl as DDE events come as windows events and are not translated by Qt.
*/
virtual bool winEvent(MSG *message, long '''result);
 
// —— helpers for the file registration ——————————————————
/'''*
* virtual function that must be implemented by the derived class to react to the open command
* from Windows.
*
* <code>param filePath file that was selected in the explorer
*/
virtual void ddeOpenFile(const QString&amp;amp; filePath);
 
/'''*
* virtual function that must be implemented by the derived class to react to the new command
* from Windows.
*
* </code>param filePath file that was selected in the explorer
*/
virtual void ddeNewFile(const QString&amp;amp; filePath);
 
/'''*
* virtual function that must be implemented by the derived class to react to the print command
* from Windows.
*
* <code>param filePath file that was selected in the explorer
*/
virtual void ddePrintFile(const QString&amp;amp; filePath);
 
/'''*
* virtual function that must be implemented by get custom dde commands from the explorer. If, e.g.
* a printo or copy command should be available in explorer and they are registered via registerCommand,
* this function is called.
*
* </code>param command name of the command
* <code>param params parameter string, containing the hole stuff, also " and commas.
*
* </code>note a command like this [compare("%1")] will result in the parameters:
command = "compare";
params = "quot;<filepath>quot;";
*/
virtual void executeUnknownDdeCommand(const QString&amp;amp; command, const QString&amp;amp; params);
 
/'''*
* Call this method to register the file type in Windows. It creates the default command
* which means the app is started with the file to open as parameter. If <code>arg registerForDDE
* is true, the dde events are also created so the opening of a file is done in typical MDI
* behavior (all files open in the same app).
*
* </code>param documentId id of the document, typically <Application>.Document —> see in registry, e.g. "GiMdi.Document"
* <code>param fileTypeName free name of the file type, e.g. "MDI Text Editor Document"
* </code>param fileExtension File extension, including the dot (e.g. ".gidoc")
* <code>param appIconIndex index of the app icon to use for the file in the windows explorer, typically the application icon
* </code>param registerForDDE true if DDE should be used (typical for MDI apps), typically false for SDI apps.
* <code>param commands a combination of the commands to install.
*
* </code>note If more then the default commands are needed, then subsequent calls of registerCommand are needed.
*
* <code>note DDEOpen leads to the DDE command: [open("%1)]
DDENew leads to the DDE command: [new("%1)]
DDEPrint leads to the DDE command: [print("%1)]
*/
void registerFileType(const QString&amp;amp; documentId,
const QString&amp;amp; fileTypeName,
const QString&amp;amp; fileExtension,
qint32 appIconIndex = 0,
bool registerForDDE = false,
DdeCommands commands = DDEOpen);
 
/'''*
* registeres one command for a given file type. It is called for the pre defined DDE command
* types from registerFileType. if more then the normal commands are needed, it can be called
* in addition to registerFileType.
*
* </code>code
MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags flags) :
DocumentWindow(parent, flags)
{
 
registerFileType("GiMdi.Document", "MDI Text Editor Document", ".gidoc", 0, true);
registerCommand("fancyCommand", "GiMdi.Document", "-fancy %1", "[fancy(quot;%1quot;)]");
enableShellOpen();
 
}
<code>endcode
*/
void registerCommand(const QString&amp;amp; command,
const QString&amp;amp; documentId,
const QString cmdLineArg = QString::null,
const QString ddeCommand = QString::null);
 
/'''*
* Call this method to enable the user to open data files associated with your application
* by double-clicking the files in the windows file manager.
*
* Use it together with registerFileType to register the fspezified file types or provida a
* registry file ('''.reg) which does this.
*/
void enableShellOpen();
 
 
private:
// —— privat helpers ————————————————————————
/**
* implementation of the WM_DDE_INITIATE windows message
*/
bool ddeInitiate(MSG''' message, long* result);
 
/**
* implementation of the WM_DDE_EXECUTE windows message
*/
bool ddeExecute(MSG''' message, long* result);
 
/**
* implementation of the WM_DDE_TERMINATE windows message
*/
bool ddeTerminate(MSG''' message, long* result);
 
/**
* Sets specified value in the registry under HKCU\Software\Classes, which is mapped to HKCR then.
*/
bool SetHkcrUserRegKey(QString key, const QString&amp;amp; value, const QString&amp;amp; valueName = QString::null);
 
/'''*
* this method is called to do the DDE command handling. It does argument splitting and then calls
* ddeOpenFile, ddeNewFile, ddePrintFile or executeUnknownDdeCommand.
*/
void executeDdeCommand(const QString&amp;amp; command, const QString&amp;amp; params);
 
// —— members ——————————————————————————-
bool m_registerForDDE; /< used to identfy, if the dde commands should be written to the registry*/
QString m_appAtomName; /*'''< the name of the application, without file extension*/
QString m_systemTopicAtomName; /*'''< the name of the system topic atom, typically "System"*/
ATOM m_appAtom; /*'''< The windows atom needed for DDE communication*/
ATOM m_systemTopicAtom; /*'''< The windows system topic atom needed for DDE communication*/
// —— not allowed members ——————————————————————-
};


Q_DECLARE_OPERATORS_FOR_FLAGS(DocumentWindow::DdeCommands)
Q_DECLARE_OPERATORS_FOR_FLAGS(DocumentWindow::DdeCommands)


#endif // WIDGET_H<br /></code>
#endif // WIDGET_H
</code>


=== DocumentWindow.cpp ===
=== DocumentWindow.cpp ===


<code><br />// ————————————————————————————————-<br />/**<br /> * </code>file<br /> * <code>brief<br /> * </code>author Gerolf Reinwardt<br /> * <code>date 30.01.2011<br /> *<br /> * Copyright © 2011, Gerolf Reinwardt. All rights reserved.<br /> *<br /> * Simplified BSD License<br /> *<br /> * Redistribution and use in source and binary forms, with or without modification, are<br /> * permitted provided that the following conditions are met:<br /> *<br /> * 1. Redistributions of source code must retain the above copyright notice, this list of<br /> * conditions and the following disclaimer.<br /> *<br /> * 2. Redistributions in binary form must reproduce the above copyright notice, this list<br /> * of conditions and the following disclaimer in the documentation and/or other materials<br /> * provided with the distribution.<br /> *<br /> * THIS SOFTWARE IS PROVIDED BY &lt;COPYRIGHT HOLDER&amp;gt; ``AS IS'' AND ANY EXPRESS OR IMPLIED<br /> * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND<br /> * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL &lt;COPYRIGHT HOLDER&amp;gt; OR<br /> * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR<br /> * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR<br /> * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON<br /> * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING<br /> * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF<br /> * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.<br /> *<br /> * The views and conclusions contained in the software and documentation are those of the<br /> * authors and should not be interpreted as representing official policies, either expressed<br /> * or implied, of Gerolf Reinwardt.<br /> '''/<br />// ————————————————————————————————-
<code>
<br />// —— general includes —————————————————————————<br />#include &lt;windows.h&amp;gt;<br />#include &lt;QtGui/QMessageBox&amp;gt;<br />#include &lt;QtGui/QApplication&amp;gt;<br />#include &lt;QtCore/QDir&amp;gt;<br />#include &lt;QtCore/QFileInfo&amp;gt;<br />#include &lt;QtCore/QRegExp&amp;gt;
// ————————————————————————————————-
<br />// —— local includes —————————————————————————-<br />#include &quot;documentwindow.h&amp;quot;
/**
* </code>file
* <code>brief
* </code>author Gerolf Reinwardt
* <code>date 30.01.2011
*
* Copyright © 2011, Gerolf Reinwardt. All rights reserved.
*
* Simplified BSD License
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of Gerolf Reinwardt.
*/
// ————————————————————————————————-
 
// —— general includes —————————————————————————
#include <windows.h>
#include <QtGui/QMessageBox>
#include <QtGui/QApplication>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QRegExp>
 
// —— local includes —————————————————————————-
#include "documentwindow.h"


<br />// —— construction ——————————————————————————<br />DocumentWindow::DocumentWindow(QWidget''' parent, Qt::WindowFlags flags) :<br /> QMainWindow(parent, flags),<br /> m_registerForDDE(false),<br /> m_appAtomName(),<br /> m_systemTopicAtomName(&quot;system&amp;quot;),<br /> m_appAtom(0),<br /> m_systemTopicAtom(0)<br />{<br /> QFileInfo fi(qApp-&gt;applicationFilePath());<br /> m_appAtomName = fi.baseName();<br />}


DocumentWindow::~DocumentWindow()<br />{<br /> if(0 != m_appAtom)<br /> {<br /> ::GlobalDeleteAtom(m_appAtom);<br /> m_appAtom = 0;<br /> }<br /> if(0 != m_systemTopicAtom)<br /> {<br /> ::GlobalDeleteAtom(m_systemTopicAtom);<br /> m_systemTopicAtom = 0;<br /> }<br />}
// —— construction ——————————————————————————
DocumentWindow::DocumentWindow(QWidget''' parent, Qt::WindowFlags flags) :
QMainWindow(parent, flags),
m_registerForDDE(false),
m_appAtomName(),
m_systemTopicAtomName("system"),
m_appAtom(0),
m_systemTopicAtom(0)
{
QFileInfo fi(qApp->applicationFilePath());
m_appAtomName = fi.baseName();
}


// —— operators ———————————————————————————<br />// —— methods ————————————————————————————<br />// —— accessors ———————————————————————————<br />// —— public slots ——————————————————————————<br />// —— protected slots —————————————————————————<br />// —— events ————————————————————————————<br />bool DocumentWindow::winEvent(MSG *message, long '''result)<br />{<br /> switch(message-&gt;message)<br /> {<br /> case WM_DDE_INITIATE:<br /> return ddeInitiate(message, result);<br /> break;<br /> case WM_DDE_EXECUTE:<br /> return ddeExecute(message, result);<br /> break;<br /> case WM_DDE_TERMINATE:<br /> return ddeTerminate(message, result);<br /> break;<br /> }
DocumentWindow::~DocumentWindow()
<br /> return QMainWindow::winEvent(message, result);<br />}
{
<br />void DocumentWindow::ddeOpenFile&amp;amp;#40;const QString&amp;amp;&amp;#41;<br />{<br /> // this method will be overwritten, if the application uses the dde open command<br />}
if(0 != m_appAtom)
<br />void DocumentWindow::ddeNewFile&amp;amp;#40;const QString&amp;amp;&amp;#41;<br />{<br /> // this method will be overwritten, if the application uses the dde new command<br />}
{
<br />void DocumentWindow::ddePrintFile&amp;amp;#40;const QString&amp;amp;&amp;#41;<br />{<br /> // this method will be overwritten, if the application uses the dde print command<br />}
::GlobalDeleteAtom(m_appAtom);
<br />void DocumentWindow::executeUnknownDdeCommand(const QString&amp;amp;, const QString&amp;amp;)<br />{<br /> // this method will be overwritten, if the application uses other commands,<br /> // then open, new and print via DDE and Explorer<br />}
m_appAtom = 0;
<br />void DocumentWindow::registerFileType(const QString&amp;amp; documentId,<br /> const QString&amp;amp; fileTypeName,<br /> const QString&amp;amp; fileExtension,<br /> qint32 appIconIndex,<br /> bool registerForDDE,<br /> DdeCommands commands)<br />{<br /> // first register the type ID of our server<br /> if (!SetHkcrUserRegKey(documentId, fileTypeName))<br /> return;
}
<br /> if (!SetHkcrUserRegKey(QString(&quot;%1DefaultIcon&amp;quot;).arg(documentId),<br /> QString(&quot;quot;%1quot;,%2&amp;quot;).arg(QDir::toNativeSeparators(qApp-&gt;applicationFilePath())).arg(appIconIndex)))<br /> return;
if(0 != m_systemTopicAtom)
<br /> m_registerForDDE = registerForDDE;
{
<br /> if(commands &amp; DDEOpen)<br /> registerCommand(&quot;Open&amp;quot;, documentId, &quot;quot;%1quot;&quot;, &quot;[open(quot;%1quot;)]&quot;);<br /> if(commands &amp; DDENew)<br /> registerCommand(&quot;New&amp;quot;, documentId, &quot;-new quot;%1quot;&quot;, &quot;[new(quot;%1quot;)]&quot;);<br /> if(commands &amp; DDEPrint)<br /> registerCommand(&quot;Print&amp;quot;, documentId, &quot;<s>print quot;%1quot;&quot;, &quot;[print(quot;%1quot;)]&quot;);
::GlobalDeleteAtom(m_systemTopicAtom);
<br /> LONG lSize = _MAX_PATH * 2;<br /> wchar_t szTempBuffer[_MAX_PATH * 2];<br /> LONG lResult = ::RegQueryValue(HKEY_CLASSES_ROOT,<br /> (const wchar_t*)fileExtension.utf16(),<br /> szTempBuffer,<br /> &amp;lSize);
m_systemTopicAtom = 0;
<br /> QString temp = QString::fromUtf16((unsigned short*)szTempBuffer);
}
<br /> if (lResult != ERROR_SUCCESS || temp.isEmpty() || temp == documentId)<br /> {<br /> // no association for that suffix<br /> if (!SetHkcrUserRegKey(fileExtension, documentId))<br /> return;
}
<br /> SetHkcrUserRegKey(QString(&quot;%1ShellNew&amp;quot;).arg(fileExtension), QLatin1String(&quot;&quot;), QLatin1String(&quot;NullFile&amp;quot;));<br /> }<br />}
<br />void DocumentWindow::registerCommand(const QString&amp;amp; command,<br /> const QString&amp;amp; documentId,<br /> const QString cmdLineArg,<br /> const QString ddeCommand)<br />{<br /> QString commandLine = QDir::toNativeSeparators(qApp</s>&gt;applicationFilePath());<br /> commandLine.prepend(QLatin1String(&quot;quot;&quot;));<br /> commandLine.append(QLatin1String(&quot;quot;&quot;));
<br /> if(!cmdLineArg.isEmpty())<br /> {<br /> commandLine.append(QChar(' '));<br /> commandLine.append(cmdLineArg);<br /> }
<br /> if (!SetHkcrUserRegKey(QString(&quot;%1shell%2command&amp;quot;).arg(documentId).arg(command), commandLine))<br /> return; // just skip it
<br /> if(m_registerForDDE)<br /> {<br /> if (!SetHkcrUserRegKey(QString(&quot;%1shell%2ddeexec&amp;quot;).arg(documentId).arg(command), ddeCommand))<br /> return;
<br /> if (!SetHkcrUserRegKey(QString(&quot;%1shell%2ddeexecapplication&amp;quot;).arg(documentId).arg(command), m_appAtomName))<br /> return;
<br /> if (!SetHkcrUserRegKey(QString(&quot;%1shell%2ddeexectopic&amp;quot;).arg(documentId).arg(command), m_systemTopicAtomName))<br /> return;<br /> }<br />}
<br />void DocumentWindow::enableShellOpen()<br />{<br /> if((0 != m_appAtom) || (0 != m_systemTopicAtom))<br /> return;
<br /> m_appAtom = ::GlobalAddAtomW((const wchar_t''')m_appAtomName.utf16());<br /> m_systemTopicAtom = ::GlobalAddAtomW((const wchar_t*)m_systemTopicAtomName.utf16());<br />}


// —— private slots ——————————————————————————<br />// —— private helpers —————————————————————————<br />bool DocumentWindow::ddeInitiate(MSG* message, long* result)<br />{<br /> if( (0 != LOWORD (message-&amp;gt;lParam)) &amp;&amp;<br /> (0 != HIWORD (message-&amp;gt;lParam)) &amp;&amp;<br /> (LOWORD (message-&amp;gt;lParam)  m_appAtom) &amp;amp;&amp;amp;
// —— operators ———————————————————————————
         (HIWORD(message-&amp;gt;lParam)  m_systemTopicAtom))<br /> {<br /> // make duplicates of the incoming atoms (really adding a reference)<br /> wchar_t atomName[_MAX_PATH];<br /> Q_ASSERT(::GlobalGetAtomNameW(m_appAtom, atomName, _MAX_PATH - 1) != 0);<br /> Q_ASSERT(::GlobalAddAtomW(atomName)  m_appAtom);
// —— methods ————————————————————————————
// —— accessors ———————————————————————————
// —— public slots ——————————————————————————
// —— protected slots —————————————————————————
// —— events ————————————————————————————
bool DocumentWindow::winEvent(MSG *message, long '''result)
{
switch(message->message)
{
case WM_DDE_INITIATE:
return ddeInitiate(message, result);
break;
case WM_DDE_EXECUTE:
return ddeExecute(message, result);
break;
case WM_DDE_TERMINATE:
return ddeTerminate(message, result);
break;
}
 
return QMainWindow::winEvent(message, result);
}
 
void DocumentWindow::ddeOpenFile(const QString&amp;amp;)
{
// this method will be overwritten, if the application uses the dde open command
}
 
void DocumentWindow::ddeNewFile(const QString&amp;amp;)
{
// this method will be overwritten, if the application uses the dde new command
}
 
void DocumentWindow::ddePrintFile(const QString&amp;amp;)
{
// this method will be overwritten, if the application uses the dde print command
}
 
void DocumentWindow::executeUnknownDdeCommand(const QString&amp;amp;, const QString&amp;amp;)
{
// this method will be overwritten, if the application uses other commands,
// then open, new and print via DDE and Explorer
}
 
void DocumentWindow::registerFileType(const QString&amp;amp; documentId,
const QString&amp;amp; fileTypeName,
const QString&amp;amp; fileExtension,
qint32 appIconIndex,
bool registerForDDE,
DdeCommands commands)
{
// first register the type ID of our server
if (!SetHkcrUserRegKey(documentId, fileTypeName))
return;
 
if (!SetHkcrUserRegKey(QString("%1DefaultIcon").arg(documentId),
QString("quot;%1quot;,%2").arg(QDir::toNativeSeparators(qApp->applicationFilePath())).arg(appIconIndex)))
return;
 
m_registerForDDE = registerForDDE;
 
if(commands &amp; DDEOpen)
registerCommand("Open", documentId, "quot;%1quot;", "[open(quot;%1quot;)]");
if(commands &amp; DDENew)
registerCommand("New", documentId, "-new quot;%1quot;", "[new(quot;%1quot;)]");
if(commands &amp; DDEPrint)
registerCommand("Print", documentId, "-print quot;%1quot;", "[print(quot;%1quot;)]");
 
LONG lSize = _MAX_PATH * 2;
wchar_t szTempBuffer[_MAX_PATH * 2];
LONG lResult = ::RegQueryValue(HKEY_CLASSES_ROOT,
(const wchar_t*)fileExtension.utf16(),
szTempBuffer,
&amp;lSize);
 
QString temp = QString::fromUtf16((unsigned short*)szTempBuffer);
 
if (lResult != ERROR_SUCCESS || temp.isEmpty() || temp == documentId)
{
// no association for that suffix
if (!SetHkcrUserRegKey(fileExtension, documentId))
return;
 
SetHkcrUserRegKey(QString("%1ShellNew").arg(fileExtension), QLatin1String(""), QLatin1String("NullFile"));
}
}
 
void DocumentWindow::registerCommand(const QString&amp;amp; command,
const QString&amp;amp; documentId,
const QString cmdLineArg,
const QString ddeCommand)
{
QString commandLine = QDir::toNativeSeparators(qApp->applicationFilePath());
commandLine.prepend(QLatin1String("quot;"));
commandLine.append(QLatin1String("quot;"));
 
if(!cmdLineArg.isEmpty())
{
commandLine.append(QChar(' '));
commandLine.append(cmdLineArg);
}
 
if (!SetHkcrUserRegKey(QString("%1shell%2command").arg(documentId).arg(command), commandLine))
return; // just skip it
 
if(m_registerForDDE)
{
if (!SetHkcrUserRegKey(QString("%1shell%2ddeexec").arg(documentId).arg(command), ddeCommand))
return;
 
if (!SetHkcrUserRegKey(QString("%1shell%2ddeexecapplication").arg(documentId).arg(command), m_appAtomName))
return;
 
if (!SetHkcrUserRegKey(QString("%1shell%2ddeexectopic").arg(documentId).arg(command), m_systemTopicAtomName))
return;
}
}
 
void DocumentWindow::enableShellOpen()
{
if((0 != m_appAtom) || (0 != m_systemTopicAtom))
return;
 
m_appAtom = ::GlobalAddAtomW((const wchar_t''')m_appAtomName.utf16());
m_systemTopicAtom = ::GlobalAddAtomW((const wchar_t*)m_systemTopicAtomName.utf16());
}
 
// —— private slots ——————————————————————————
// —— private helpers —————————————————————————
bool DocumentWindow::ddeInitiate(MSG* message, long* result)
{
if( (0 != LOWORD (message->lParam)) &amp;&amp;
(0 != HIWORD (message->lParam)) &amp;&amp;
(LOWORD (message->lParam)  m_appAtom) &amp;amp;&amp;amp;
         (HIWORD(message->lParam)  m_systemTopicAtom))
{
// make duplicates of the incoming atoms (really adding a reference)
wchar_t atomName[_MAX_PATH];
Q_ASSERT(::GlobalGetAtomNameW(m_appAtom, atomName, _MAX_PATH - 1) != 0);
Q_ASSERT(::GlobalAddAtomW(atomName)  m_appAtom);
         Q_ASSERT(::GlobalGetAtomNameW(m_systemTopicAtom, atomName, _MAX_PATH - 1) != 0);
         Q_ASSERT(::GlobalGetAtomNameW(m_systemTopicAtom, atomName, _MAX_PATH - 1) != 0);
         Q_ASSERT(::GlobalAddAtomW(atomName)  m_systemTopicAtom);
         Q_ASSERT(::GlobalAddAtomW(atomName)  m_systemTopicAtom);


// send the WM_DDE_ACK (caller will delete duplicate atoms)<br /> ::SendMessage((HWND)message-&gt;wParam, WM_DDE_ACK, (WPARAM)winId(), MAKELPARAM (m_appAtom, m_systemTopicAtom));<br /> }<br /> '''result = 0;<br /> return true;<br />}
// send the WM_DDE_ACK (caller will delete duplicate atoms)
<br />bool DocumentWindow::ddeExecute(MSG''' message, long* result)<br />{<br /> // unpack the DDE message<br /> UINT_PTR unused;<br /> HGLOBAL hData;<br /> //IA64: Assume DDE LPARAMs are still 32-bit<br /> Q_ASSERT(::UnpackDDElParam(WM_DDE_EXECUTE, message-&gt;lParam, &amp;unused, (UINT_PTR*)&amp;hData));
::SendMessage((HWND)message->wParam, WM_DDE_ACK, (WPARAM)winId(), MAKELPARAM (m_appAtom, m_systemTopicAtom));
}
'''result = 0;
return true;
}
 
bool DocumentWindow::ddeExecute(MSG''' message, long* result)
{
// unpack the DDE message
UINT_PTR unused;
HGLOBAL hData;
//IA64: Assume DDE LPARAMs are still 32-bit
Q_ASSERT(::UnpackDDElParam(WM_DDE_EXECUTE, message->lParam, &amp;unused, (UINT_PTR*)&amp;hData));
 
QString command = QString::fromWCharArray((LPCWSTR)::GlobalLock(hData));
::GlobalUnlock(hData);
 
// acknowledge now - before attempting to execute
::PostMessage((HWND)message->wParam, WM_DDE_ACK, (WPARAM)winId(),
//IA64: Assume DDE LPARAMs are still 32-bit
ReuseDDElParam(message->lParam, WM_DDE_EXECUTE, WM_DDE_ACK, (UINT)0x8000, (UINT_PTR)hData));
 
// don't execute the command when the window is disabled
if (!isEnabled())
{
'''result = 0;
return true;
}
 
QRegExp regCommand("<sup>$");
if(regCommand.exactMatch(command))
{
executeDdeCommand(regCommand.cap(1), regCommand.cap(2));
}
 
'''result = 0;
return true;
}
 
bool DocumentWindow::ddeTerminate(MSG''' message, long* result)
{
// The client or server application should respond by posting a WM_DDE_TERMINATE message.
::PostMessageW((HWND)message->wParam, WM_DDE_TERMINATE, (WPARAM)winId(), message->lParam);
return true;
}
 
bool DocumentWindow::SetHkcrUserRegKey(QString key, const QString&amp;amp; value, const QString&amp;amp; valueName)
{
HKEY hKey;
 
key.prepend("SoftwareClasses");
 
LONG lRetVal = RegCreateKey(HKEY_CURRENT_USER,
(const wchar_t*)key.utf16(),
&amp;hKey);
 
if(ERROR_SUCCESS == lRetVal)
{
LONG lResult = ::RegSetValueExW(hKey,
valueName.isEmpty() ? 0 : (const wchar_t*)valueName.utf16(),
0,
REG_SZ,
(CONST BYTE*)value.utf16(),
(value.length() + 1) * sizeof(wchar_t));


QString command = QString::fromWCharArray((LPCWSTR)::GlobalLock(hData));<br /> ::GlobalUnlock(hData);
if(::RegCloseKey(hKey) ERROR_SUCCESS &amp;amp;&amp;amp; lResult  ERROR_SUCCESS)
return true;


// acknowledge now - before attempting to execute<br /> ::PostMessage((HWND)message-&gt;wParam, WM_DDE_ACK, (WPARAM)winId(),<br /> //IA64: Assume DDE LPARAMs are still 32-bit<br /> ReuseDDElParam(message-&gt;lParam, WM_DDE_EXECUTE, WM_DDE_ACK, (UINT)0x8000, (UINT_PTR)hData));
QMessageBox::warning(0, QString("Error in setting Registry values"),
QString("registration database update failed for key '%s'.").arg(key));
}
else
{
wchar_t buffer[4096];
::FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, 0, lRetVal, 0, buffer, 4096, 0);
QString szText = QString::fromUtf16((const ushort*)buffer);
QMessageBox::warning(this, QString("Error in setting Registry values"), szText);
}
return false;
}


// don't execute the command when the window is disabled<br /> if (!isEnabled())<br /> {<br /> '''result = 0;<br /> return true;<br /> }
void DocumentWindow::executeDdeCommand(const QString&amp;amp; command, const QString&amp;amp; params)
<br /> QRegExp regCommand(&quot;<sup>$&amp;quot;);<br /> if(regCommand.exactMatch(command))<br /> {<br /> executeDdeCommand(regCommand.cap(1), regCommand.cap(2));<br /> }
{
<br /> '''result = 0;<br /> return true;<br />}
QRegExp regCommand("</sup>quot;(.''')quot;$");
<br />bool DocumentWindow::ddeTerminate(MSG''' message, long* result)<br />{<br /> // The client or server application should respond by posting a WM_DDE_TERMINATE message.<br /> ::PostMessageW((HWND)message-&gt;wParam, WM_DDE_TERMINATE, (WPARAM)winId(), message-&gt;lParam);<br /> return true;<br />}
bool singleCommand = regCommand.exactMatch(params);
<br />bool DocumentWindow::SetHkcrUserRegKey(QString key, const QString&amp;amp; value, const QString&amp;amp; valueName)<br />{<br /> HKEY hKey;
if((0  command.compare("open", Qt::CaseInsensitive)) &amp;amp;&amp;amp; singleCommand)
<br /> key.prepend(&quot;SoftwareClasses&quot;);
     {
<br /> LONG lRetVal = RegCreateKey(HKEY_CURRENT_USER,<br /> (const wchar_t*)key.utf16(),<br /> &amp;hKey);
         ddeOpenFile(regCommand.cap(1));
<br /> if(ERROR_SUCCESS == lRetVal)<br /> {<br /> LONG lResult = ::RegSetValueExW(hKey,<br /> valueName.isEmpty() ? 0 : (const wchar_t*)valueName.utf16(),<br /> 0,<br /> REG_SZ,<br /> (CONST BYTE*)value.utf16(),<br /> (value.length() + 1) * sizeof(wchar_t));
     }
<br /> if(::RegCloseKey(hKey)  ERROR_SUCCESS &amp;amp;&amp;amp; lResult  ERROR_SUCCESS)<br /> return true;
     else if((0  command.compare("new", Qt::CaseInsensitive)) &amp;&amp; singleCommand)
<br /> QMessageBox::warning(0, QString(&quot;Error in setting Registry values&amp;quot;),<br /> QString(&quot;registration database update failed for key '%s'.&quot;).arg(key));<br /> }<br /> else<br /> {<br /> wchar_t buffer[4096];<br /> ::FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, 0, lRetVal, 0, buffer, 4096, 0);<br /> QString szText = QString::fromUtf16((const ushort*)buffer);<br /> QMessageBox::warning(this, QString(&quot;Error in setting Registry values&amp;quot;), szText);<br /> }<br /> return false;<br />}
{
<br />void DocumentWindow::executeDdeCommand(const QString&amp;amp; command, const QString&amp;amp; params)<br />{<br /> QRegExp regCommand(&quot;</sup>quot;(.''')quot;$&amp;quot;);<br /> bool singleCommand = regCommand.exactMatch(params);<br /> if((0  command.compare(&amp;quot;open&amp;quot;, Qt::CaseInsensitive)) &amp;amp;&amp;amp; singleCommand)
ddeNewFile(regCommand.cap(1));
     &amp;#123;
}
         ddeOpenFile&amp;amp;#40;regCommand.cap(1&amp;amp;#41;);
else if((0 == command.compare("print", Qt::CaseInsensitive)) &amp;&amp; singleCommand)
     &amp;#125;
{
     else if((0  command.compare(&quot;new&amp;quot;, Qt::CaseInsensitive)) &amp;&amp; singleCommand)<br /> {<br /> ddeNewFile&amp;amp;#40;regCommand.cap(1&amp;amp;#41;);<br /> }<br /> else if((0 == command.compare(&quot;print&amp;quot;, Qt::CaseInsensitive)) &amp;&amp; singleCommand)<br /> {<br /> ddePrintFile&amp;amp;#40;regCommand.cap(1&amp;amp;#41;);<br /> }<br /> else<br /> {<br /> executeUnknownDdeCommand(command, params);<br /> }<br />}
ddePrintFile(regCommand.cap(1));
}
else
{
executeUnknownDdeCommand(command, params);
}
}


</code>
</code>
Line 157: Line 717:
== Future extensions ==
== 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: &quot;qtdevnet-registereditorfiletype&amp;quot;:https://www.gitorious.org/qtdevnet-wiki-mvc/qtdevnet-registereditorfiletype
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":https://www.gitorious.org/qtdevnet-wiki-mvc/qtdevnet-registereditorfiletype


== Versions ==
== Versions ==

Revision as of 09:46, 25 February 2015


English | Deutsch

[toc align_right="yes" depth="3"]

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&amp;gt;" in HKCR which contains the file type name. In HKCRamp;lt;file type name&amp;gt; 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:.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:

HKEY_CLASSES_ROOT
 idoc
 "Default"="GiMdi.Document"
 "NullFile"=""

.Document
 "Default"="MDI Text Editor Document"
 ]
 "Default"="E:.exe,0"
 "Default"="E:.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:

HKEY_CLASSES_ROOT
 .Document
 "Default"="[open(quot;%1quot;)]"
 ]
 "Default"="SimpleCryptIoDevided"
 "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":http://doc.qt.nokia.com/4.7/mainwindows-mdi.html

class MainWindow : public DocumentWindow
{

protected:
 virtual void ddeOpenFile(const QString&amp;amp; filePath);
}

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

MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags flags) :
 DocumentWindow(parent, flags)
{
 
 registerFileType("GiMdi.Document", // Document type name
 "MDI Text Editor Document",// User readable file type name
 ".gidoc", // file extension
 0, // index of the icon to use for the files.
 true); // register for DDE events
 enableShellOpen();
 
}

endcode

and reimplement ddeFileOpen

void MainWindow::ddeOpenFile(const QString&amp; filePath) {

MdiChild child = createMdiChild();
if (child->loadFile(filePath))
{
statusBar()->showMessage(tr("File loaded"), 2000);
child->show();
}
else
{
child->close();
}

}

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.

h2. Use the DocumentWindow sources

h3. DocumentWindow.h

// ————————————————————————————————- /*

*

file
 *

brief *

author Gerolf Reinwardt
 *

date 30. march 2011

*
* Copyright © 2011, Gerolf Reinwardt. All rights reserved.
*
* Simplified BSD License
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of Gerolf Reinwardt.
*/

// ————————————————————————————————-

  1. ifndef WIDGET_H
  2. define WIDGET_H

// —— general includes —————————————————————————

  1. include <windows.h>
  2. include <QtGui/QMainWindow>

// —— local includes —————————————————————————- // —— pre defines ——————————————————————————-

// —— class definition ————————————————————————— /*

*

short This class implements a main window with the ability to register file types on MS Windows and
 * react on the corresponding DDE events to open / print the files in an Windows MDI typical manner.
 *
 * The usage is fairly easy. Derive your own MainWindow class from DocumentWindow instead of QMainWindow.
 * Inside your constructor, call registerFileType and enableShellOpen. The axample is build on top of the
 * Qt MDI Example (http://doc.qt.nokia.com/4.7/mainwindows-mdi.html)
 *
 *

code

MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags flags) :
DocumentWindow(parent, flags)
{
…

registerFileType("GiMdi.Document", "MDI Text Editor Document", ".gidoc", 0, true);

enableShellOpen();

setWindowTitle(tr("MDI"));

setUnifiedTitleAndToolBarOnMac(true);
}
endcode
 *
 * Aditionally, the actions must be performed by overwriting one or more of:
 *

li ddeOpenFile *

li ddeNewFile
 *

li ddePrintFile *

li executeUnknownDdeCommand
 *
 *

code

void MainWindow::ddeOpenFile(const QString&amp; filePath)
{
MdiChild child = createMdiChild();
if (child->loadFile(filePath))
{
statusBar()->showMessage(tr("File loaded"), 2000);
child->show();
}
else
{
child->close();
}
}
endcode
'''
 */
class DocumentWindow : public QMainWindow
{
 Q_OBJECT
public:
 // —— enums ———————————————————————————
 /'''*
 * Known DDE command. These commands are typically used
 */
 enum DdeCommand {
 DDEOpen = 0x0001, /< open a file via explorer*/
 DDENew = 0x0002, /*'''< create a new file via explorer*/
 DDEPrint = 0x0004, /*'''< print a file via explorer*/
 };
 Q_DECLARE_FLAGS(DdeCommands, DdeCommand)

// —— construction —————————————————————————
 /**
 * Constructor.
 *
 * Creates a DocumentWindow with a given

arg parent and arg flags.

*/
explicit DocumentWindow(QWidget parent = 0, Qt::WindowFlags flags = 0);

/**

* Destructor
*/
~DocumentWindow();
// —— operators ——————————————————————————
// —— methods ——————————————————————————-
// —— accessors ——————————————————————————
// —— members ——————————————————————————-

protected:

// —— events ———————————————————————————
/*
* reimpl as DDE events come as windows events and are not translated by Qt.
*/
virtual bool winEvent(MSG *message, long result);
// —— helpers for the file registration ——————————————————
/*
* virtual function that must be implemented by the derived class to react to the open command
* from Windows.
*

*

param filePath file that was selected in the explorer
 */
 virtual void ddeOpenFile(const QString&amp;amp; filePath);

 /'''*
 * virtual function that must be implemented by the derived class to react to the new command
 * from Windows.
 *
 *

param filePath file that was selected in the explorer

*/
virtual void ddeNewFile(const QString&amp; filePath);
/*
* virtual function that must be implemented by the derived class to react to the print command
* from Windows.
*

*

param filePath file that was selected in the explorer
 */
 virtual void ddePrintFile(const QString&amp;amp; filePath);

 /'''*
 * virtual function that must be implemented by get custom dde commands from the explorer. If, e.g.
 * a printo or copy command should be available in explorer and they are registered via registerCommand,
 * this function is called.
 *
 *

param command name of the command *

param params parameter string, containing the hole stuff, also " and commas.
 *
 *

note a command like this [compare("%1")] will result in the parameters:

command = "compare";
params = "quot;<filepath>quot;";
*/
virtual void executeUnknownDdeCommand(const QString&amp; command, const QString&amp; params);
/*
* Call this method to register the file type in Windows. It creates the default command

* which means the app is started with the file to open as parameter. If

arg registerForDDE
 * is true, the dde events are also created so the opening of a file is done in typical MDI
 * behavior (all files open in the same app).
 *
 *

param documentId id of the document, typically <Application>.Document —> see in registry, e.g. "GiMdi.Document" *

param fileTypeName free name of the file type, e.g. "MDI Text Editor Document"
 *

param fileExtension File extension, including the dot (e.g. ".gidoc") *

param appIconIndex index of the app icon to use for the file in the windows explorer, typically the application icon
 *

param registerForDDE true if DDE should be used (typical for MDI apps), typically false for SDI apps. *

param commands a combination of the commands to install.
 *
 *

note If more then the default commands are needed, then subsequent calls of registerCommand are needed.

*

*

note DDEOpen leads to the DDE command: [open("%1)]
 DDENew leads to the DDE command: [new("%1)]
 DDEPrint leads to the DDE command: [print("%1)]
 */
 void registerFileType(const QString&amp;amp; documentId,
 const QString&amp;amp; fileTypeName,
 const QString&amp;amp; fileExtension,
 qint32 appIconIndex = 0,
 bool registerForDDE = false,
 DdeCommands commands = DDEOpen);

 /'''*
 * registeres one command for a given file type. It is called for the pre defined DDE command
 * types from registerFileType. if more then the normal commands are needed, it can be called
 * in addition to registerFileType.
 *
 *

code

MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags flags) :
DocumentWindow(parent, flags)
{
…

registerFileType("GiMdi.Document", "MDI Text Editor Document", ".gidoc", 0, true);

registerCommand("fancyCommand", "GiMdi.Document", "-fancy %1", "[fancy(quot;%1quot;)]");
enableShellOpen();
…
}
endcode
 */
 void registerCommand(const QString&amp;amp; command,
 const QString&amp;amp; documentId,
 const QString cmdLineArg = QString::null,
 const QString ddeCommand = QString::null);

 /'''*
 * Call this method to enable the user to open data files associated with your application
 * by double-clicking the files in the windows file manager.
 *
 * Use it together with registerFileType to register the fspezified file types or provida a
 * registry file ('''.reg) which does this.
*/
 void enableShellOpen();


private:
 // —— privat helpers ————————————————————————
 /**
 * implementation of the WM_DDE_INITIATE windows message
 */
 bool ddeInitiate(MSG''' message, long* result);

 /**
 * implementation of the WM_DDE_EXECUTE windows message
 */
 bool ddeExecute(MSG''' message, long* result);

 /**
 * implementation of the WM_DDE_TERMINATE windows message
 */
 bool ddeTerminate(MSG''' message, long* result);

 /**
 * Sets specified value in the registry under HKCU\Software\Classes, which is mapped to HKCR then.
 */
 bool SetHkcrUserRegKey(QString key, const QString&amp;amp; value, const QString&amp;amp; valueName = QString::null);

 /'''*
 * this method is called to do the DDE command handling. It does argument splitting and then calls
 * ddeOpenFile, ddeNewFile, ddePrintFile or executeUnknownDdeCommand.
 */
 void executeDdeCommand(const QString&amp;amp; command, const QString&amp;amp; params);

 // —— members ——————————————————————————-
 bool m_registerForDDE; /< used to identfy, if the dde commands should be written to the registry*/
 QString m_appAtomName; /*'''< the name of the application, without file extension*/
 QString m_systemTopicAtomName; /*'''< the name of the system topic atom, typically "System"*/
 ATOM m_appAtom; /*'''< The windows atom needed for DDE communication*/
 ATOM m_systemTopicAtom; /*'''< The windows system topic atom needed for DDE communication*/
 // —— not allowed members ——————————————————————-
};

Q_DECLARE_OPERATORS_FOR_FLAGS(DocumentWindow::DdeCommands)

#endif // WIDGET_H

DocumentWindow.cpp

// ————————————————————————————————-
/**
 *

file *

brief
 *

author Gerolf Reinwardt *

date 30.01.2011
 *
 * Copyright © 2011, Gerolf Reinwardt. All rights reserved.
 *
 * Simplified BSD License
 *
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of
 * conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * The views and conclusions contained in the software and documentation are those of the
 * authors and should not be interpreted as representing official policies, either expressed
 * or implied, of Gerolf Reinwardt.
 */
// ————————————————————————————————-

// —— general includes —————————————————————————
#include <windows.h>
#include <QtGui/QMessageBox>
#include <QtGui/QApplication>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QRegExp>

// —— local includes —————————————————————————-
#include "documentwindow.h"


// —— construction ——————————————————————————
DocumentWindow::DocumentWindow(QWidget''' parent, Qt::WindowFlags flags) :
 QMainWindow(parent, flags),
 m_registerForDDE(false),
 m_appAtomName(),
 m_systemTopicAtomName("system"),
 m_appAtom(0),
 m_systemTopicAtom(0)
{
 QFileInfo fi(qApp->applicationFilePath());
 m_appAtomName = fi.baseName();
}

DocumentWindow::~DocumentWindow()
{
 if(0 != m_appAtom)
 {
 ::GlobalDeleteAtom(m_appAtom);
 m_appAtom = 0;
 }
 if(0 != m_systemTopicAtom)
 {
 ::GlobalDeleteAtom(m_systemTopicAtom);
 m_systemTopicAtom = 0;
 }
}

// —— operators ———————————————————————————
// —— methods ————————————————————————————
// —— accessors ———————————————————————————
// —— public slots ——————————————————————————
// —— protected slots —————————————————————————
// —— events ————————————————————————————
bool DocumentWindow::winEvent(MSG *message, long '''result)
{
 switch(message->message)
 {
 case WM_DDE_INITIATE:
 return ddeInitiate(message, result);
 break;
 case WM_DDE_EXECUTE:
 return ddeExecute(message, result);
 break;
 case WM_DDE_TERMINATE:
 return ddeTerminate(message, result);
 break;
 }

 return QMainWindow::winEvent(message, result);
}

void DocumentWindow::ddeOpenFile(const QString&amp;amp;)
{
 // this method will be overwritten, if the application uses the dde open command
}

void DocumentWindow::ddeNewFile(const QString&amp;amp;)
{
 // this method will be overwritten, if the application uses the dde new command
}

void DocumentWindow::ddePrintFile(const QString&amp;amp;)
{
 // this method will be overwritten, if the application uses the dde print command
}

void DocumentWindow::executeUnknownDdeCommand(const QString&amp;amp;, const QString&amp;amp;)
{
 // this method will be overwritten, if the application uses other commands,
 // then open, new and print via DDE and Explorer
}

void DocumentWindow::registerFileType(const QString&amp;amp; documentId,
 const QString&amp;amp; fileTypeName,
 const QString&amp;amp; fileExtension,
 qint32 appIconIndex,
 bool registerForDDE,
 DdeCommands commands)
{
 // first register the type ID of our server
 if (!SetHkcrUserRegKey(documentId, fileTypeName))
 return;

 if (!SetHkcrUserRegKey(QString("%1DefaultIcon").arg(documentId),
 QString("quot;%1quot;,%2").arg(QDir::toNativeSeparators(qApp->applicationFilePath())).arg(appIconIndex)))
 return;

 m_registerForDDE = registerForDDE;

 if(commands &amp; DDEOpen)
 registerCommand("Open", documentId, "quot;%1quot;", "[open(quot;%1quot;)]");
 if(commands &amp; DDENew)
 registerCommand("New", documentId, "-new quot;%1quot;", "[new(quot;%1quot;)]");
 if(commands &amp; DDEPrint)
 registerCommand("Print", documentId, "-print quot;%1quot;", "[print(quot;%1quot;)]");

 LONG lSize = _MAX_PATH * 2;
 wchar_t szTempBuffer[_MAX_PATH * 2];
 LONG lResult = ::RegQueryValue(HKEY_CLASSES_ROOT,
 (const wchar_t*)fileExtension.utf16(),
 szTempBuffer,
 &amp;lSize);

 QString temp = QString::fromUtf16((unsigned short*)szTempBuffer);

 if (lResult != ERROR_SUCCESS || temp.isEmpty() || temp == documentId)
 {
 // no association for that suffix
 if (!SetHkcrUserRegKey(fileExtension, documentId))
 return;

 SetHkcrUserRegKey(QString("%1ShellNew").arg(fileExtension), QLatin1String(""), QLatin1String("NullFile"));
 }
}

void DocumentWindow::registerCommand(const QString&amp;amp; command,
 const QString&amp;amp; documentId,
 const QString cmdLineArg,
 const QString ddeCommand)
{
 QString commandLine = QDir::toNativeSeparators(qApp->applicationFilePath());
 commandLine.prepend(QLatin1String("quot;"));
 commandLine.append(QLatin1String("quot;"));

 if(!cmdLineArg.isEmpty())
 {
 commandLine.append(QChar(' '));
 commandLine.append(cmdLineArg);
 }

 if (!SetHkcrUserRegKey(QString("%1shell%2command").arg(documentId).arg(command), commandLine))
 return; // just skip it

 if(m_registerForDDE)
 {
 if (!SetHkcrUserRegKey(QString("%1shell%2ddeexec").arg(documentId).arg(command), ddeCommand))
 return;

 if (!SetHkcrUserRegKey(QString("%1shell%2ddeexecapplication").arg(documentId).arg(command), m_appAtomName))
 return;

 if (!SetHkcrUserRegKey(QString("%1shell%2ddeexectopic").arg(documentId).arg(command), m_systemTopicAtomName))
 return;
 }
}

void DocumentWindow::enableShellOpen()
{
 if((0 != m_appAtom) || (0 != m_systemTopicAtom))
 return;

 m_appAtom = ::GlobalAddAtomW((const wchar_t''')m_appAtomName.utf16());
 m_systemTopicAtom = ::GlobalAddAtomW((const wchar_t*)m_systemTopicAtomName.utf16());
}

// —— private slots ——————————————————————————
// —— private helpers —————————————————————————
bool DocumentWindow::ddeInitiate(MSG* message, long* result)
{
 if( (0 != LOWORD (message->lParam)) &amp;&amp;
 (0 != HIWORD (message->lParam)) &amp;&amp;
 (LOWORD (message->lParam)  m_appAtom) &amp;amp;&amp;amp;
        (HIWORD(message->lParam)  m_systemTopicAtom))
 {
 // make duplicates of the incoming atoms (really adding a reference)
 wchar_t atomName[_MAX_PATH];
 Q_ASSERT(::GlobalGetAtomNameW(m_appAtom, atomName, _MAX_PATH - 1) != 0);
 Q_ASSERT(::GlobalAddAtomW(atomName)  m_appAtom);
        Q_ASSERT(::GlobalGetAtomNameW(m_systemTopicAtom, atomName, _MAX_PATH - 1) != 0);
        Q_ASSERT(::GlobalAddAtomW(atomName)  m_systemTopicAtom);

// send the WM_DDE_ACK (caller will delete duplicate atoms)
 ::SendMessage((HWND)message->wParam, WM_DDE_ACK, (WPARAM)winId(), MAKELPARAM (m_appAtom, m_systemTopicAtom));
 }
 '''result = 0;
 return true;
}

bool DocumentWindow::ddeExecute(MSG''' message, long* result)
{
 // unpack the DDE message
 UINT_PTR unused;
 HGLOBAL hData;
 //IA64: Assume DDE LPARAMs are still 32-bit
 Q_ASSERT(::UnpackDDElParam(WM_DDE_EXECUTE, message->lParam, &amp;unused, (UINT_PTR*)&amp;hData));

QString command = QString::fromWCharArray((LPCWSTR)::GlobalLock(hData));
 ::GlobalUnlock(hData);

// acknowledge now - before attempting to execute
 ::PostMessage((HWND)message->wParam, WM_DDE_ACK, (WPARAM)winId(),
 //IA64: Assume DDE LPARAMs are still 32-bit
 ReuseDDElParam(message->lParam, WM_DDE_EXECUTE, WM_DDE_ACK, (UINT)0x8000, (UINT_PTR)hData));

// don't execute the command when the window is disabled
 if (!isEnabled())
 {
 '''result = 0;
 return true;
 }

 QRegExp regCommand("<sup>$");
 if(regCommand.exactMatch(command))
 {
 executeDdeCommand(regCommand.cap(1), regCommand.cap(2));
 }

 '''result = 0;
 return true;
}

bool DocumentWindow::ddeTerminate(MSG''' message, long* result)
{
 // The client or server application should respond by posting a WM_DDE_TERMINATE message.
 ::PostMessageW((HWND)message->wParam, WM_DDE_TERMINATE, (WPARAM)winId(), message->lParam);
 return true;
}

bool DocumentWindow::SetHkcrUserRegKey(QString key, const QString&amp;amp; value, const QString&amp;amp; valueName)
{
 HKEY hKey;

 key.prepend("SoftwareClasses");

 LONG lRetVal = RegCreateKey(HKEY_CURRENT_USER,
 (const wchar_t*)key.utf16(),
 &amp;hKey);

 if(ERROR_SUCCESS == lRetVal)
 {
 LONG lResult = ::RegSetValueExW(hKey,
 valueName.isEmpty() ? 0 : (const wchar_t*)valueName.utf16(),
 0,
 REG_SZ,
 (CONST BYTE*)value.utf16(),
 (value.length() + 1) * sizeof(wchar_t));

 if(::RegCloseKey(hKey)  ERROR_SUCCESS &amp;amp;&amp;amp; lResult  ERROR_SUCCESS)
 return true;

 QMessageBox::warning(0, QString("Error in setting Registry values"),
 QString("registration database update failed for key '%s'.").arg(key));
 }
 else
 {
 wchar_t buffer[4096];
 ::FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, 0, lRetVal, 0, buffer, 4096, 0);
 QString szText = QString::fromUtf16((const ushort*)buffer);
 QMessageBox::warning(this, QString("Error in setting Registry values"), szText);
 }
 return false;
}

void DocumentWindow::executeDdeCommand(const QString&amp;amp; command, const QString&amp;amp; params)
{
 QRegExp regCommand("</sup>quot;(.''')quot;$");
 bool singleCommand = regCommand.exactMatch(params);
 if((0  command.compare("open", Qt::CaseInsensitive)) &amp;amp;&amp;amp; singleCommand)
    {
        ddeOpenFile(regCommand.cap(1));
    }
    else if((0  command.compare("new", Qt::CaseInsensitive)) &amp;&amp; singleCommand)
 {
 ddeNewFile(regCommand.cap(1));
 }
 else if((0 == command.compare("print", Qt::CaseInsensitive)) &amp;&amp; singleCommand)
 {
 ddePrintFile(regCommand.cap(1));
 }
 else
 {
 executeUnknownDdeCommand(command, params);
 }
}

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":https://www.gitorious.org/qtdevnet-wiki-mvc/qtdevnet-registereditorfiletype

Versions

The current code is version 1 of the code.

Version 1

This marks the first public release.

Feedback