| Plugin Development
How to develop plugins for KeePass 2.x.
|
This documentation applies to KeePass 2.x plugins. 2.x plugins are fundamentally
different from 1.x plugins. 1.x plugins cannot be loaded by KeePass 2.x.
Requirements
Before you can start developing a KeePass plugin, you need the following
prerequisites:
Step-by-Step
Tutorial
Start your favorite IDE and create a new C# Class Library project.
In this tutorial the example plugin we're developing is called SamplePlugin.
The
first thing you need to do now is to add a reference to KeePass: go
to the references dialog and select the KeePass.exe file. After
you added the reference, the namespaces KeePass and KeePassLib
should be available.
KeePass plugins all need to derive from a base KeePass plugin class (Plugin in
the KeePass.Plugins namespace).
By overriding methods of this class, you can customize the behaviour of your plugin.
A minimal plugin looks like this:
using System;
using System.Collections.Generic;
using KeePass.Plugins;
namespace SamplePlugin
{
public sealed class SamplePluginExt : Plugin
{
private IPluginHost m_host = null;
public override bool Initialize(IPluginHost host)
{
m_host = host;
return true;
}
}
}
You can find a fully documented and extended version of this simple
plugin on the KeePass plugins web page.
This plugin does exactly nothing, but it shows some important conventions
already, which must be followed by all plugins:
- The namespace must be named like the DLL file without extension. Our DLL
file is named
SamplePlugin.dll, therefore the namespace must
be called SamplePlugin.
- The main plugin class (which KeePass will instanciate when it loads your
plugin) must be called exactly the same as the namespace plus "Ext".
In this case: "SamplePlugin" + "Ext" = "SamplePluginExt".
- The main plugin class must be derived from the
KeePass.Plugins.Plugin
base class.
The Initialize function is the most important one and you
probably will always override it. In this function, you get an interface
to the KeePass internals: an IPluginHost interface reference.
By using this interface, you can access the KeePass main menu, the currently
opened database, etc. The Initialize function is called immediately
after KeePass loads your plugin. All initialization should be done in this
function (not in the constructor of your plugin class!). If you
successfully initialized everything, you must return true. If
you return false, KeePass will immediately unload your plugin.
A second function that you will need very often is the Terminate
function:
public override void Terminate()
{
}
This function is called shortly before KeePass unloads your plugin. You cannot
abort this process (it's just a notification and your last chance to clean up
all used resources, etc.). Immediately after you return from this function, KeePass
can unload your plugin. It is highly recommended to free all resources in this function
(not in the destructor of your plugin class!).
We're almost done! We now need to tell KeePass that
our file is a KeePass plugin. This is done by editing the Version Information Block
of the file. Open the file version editing dialog (in Visual Studio 2005: right-click
onto the project name - 'Properties' - button 'Assembly Information').
All fields can be assigned freely except the Product Name field (for more information
see Plugin Conventions). This field must be set to
"KeePass Plugin" (without the quotes).
That's it! Now try to compile your plugin and copy the resulting DLL
file into the KeePass directory. If you start KeePass and go to the plugins
dialog, you should see your plugin in the list of loaded plugins!
Common
Operations
Adding Menu Items:
Very often you want to add some menu items for your plugin. When clicked by the
user, your plugin should get some notification. This can be done like follows.
First of all you need to get a reference to the KeePass main menu or one of
the special submenus (like Import, Tools, etc.). For this you can
use the IPluginHost interface, which you received in the Initialize
function. Then you can use standard tool strip operations to add a new menu item for your
plugin. A very simple example, which adds a menu item to the Tools menu:
private ToolStripSeparator m_tsSeparator = null;
private ToolStripMenuItem m_tsmiMenuItem = null;
public override bool Initialize(IPluginHost host)
{
m_host = host;
// Get a reference to the 'Tools' menu item container
ToolStripItemCollection tsMenu = m_host.MainWindow.ToolsMenu.DropDownItems;
// Add a separator at the bottom
m_tsSeparator = new ToolStripSeparator();
tsMenu.Add(m_tsSeparator);
// Add menu item 'Do Something'
m_tsmiMenuItem = new ToolStripMenuItem();
m_tsmiMenuItem.Text = "Do Something";
m_tsmiMenuItem.Click += OnMenuDoSomething;
tsMenu.Add(m_tsmiMenuItem);
}
public override void Terminate()
{
// Remove all of our menu items
ToolStripItemCollection tsMenu = m_host.MainWindow.ToolsMenu.DropDownItems;
tsMenu.Remove(m_tsSeparator);
tsMenu.Remove(m_tsmiMenuItem);
}
private void OnMenuDoSomething(object sender, EventArgs e)
{
// Called when the menu item is clicked
}
If you are working with tool strips, you of course have to add a reference
to System.Windows.Forms of the .NET framework.
It is highly recommended that you remove all menu items created by
your plugin in the Terminate function (as shown in the example above).
After the Terminate function has been called, everything should
look like before loading your plugin.
In the example, we created a separator and one menu item. To this menu
item an event handler for the Click event is attached. There's nothing
special, this is all standard Windows.Forms stuff.
For examples of adding popup menus, see the SamplePlugin sample
plugin (obtainable from the KeePass plugins page).
Adding Groups and Entries:
For this, see the sample plugin and the KeePassLib documentation.
Plugin
Conventions
File Version Information Block:
KeePass uses the file version information block to detect if a DLL file is a
KeePass plugin and retrieves information from it to show in the plugins dialog.
The fields are used as follows:
- Title: Should contain the full name of the plugin.
- Description: Should contain a short description (not more than 5 lines)
of your plugin.
- Company: Should contain the author name of the plugin.
- Product Name: Must be set to
"KeePass Plugin" (without
the quotes).
- Copyright: Not used by KeePass; freely assignable by the plugin.
- Trademarks: Not used by KeePass; freely assignable by the plugin.
- Assembly Version: Should be set to the recommended KeePass version (i.e.
the KeePass version your plugin is built for).
- File Version: Should be set to the version of your plugin. It is up
to you how you are versioning your plugin builds, but it should be a scheme that
allows version comparisons (based on string comparisons).
- GUID: Not used by KeePass; freely assignable by the plugin.
Namespace and Class Naming:
The namespace must be named like the DLL file without
extension. For example, if the DLL file is named SecretImporter.dll,
you must call the namespace SecretImporter.
The plugin class must be named like the namespace plus "Ext".
For the SecretImporter plugin, this would be SecretImporterExt.
Can
KeePass 2.x Plugins be written in Unmanaged C++?
Yes and no. You can write the complete logic of your plugin in unmanaged C++ (native
Win32 APIs can be used). Anyway you must provide a managed interface to your plugin,
i.e. you must export a managed class derived from the Plugin base class
as described in the step-by-step tutorial.
Also, managed C++ will be required to modify the KeePass internals (i.e. entries,
groups, main window, ...).
For an example how to use unmanaged APIs in a managed C++ plugin assembly, see
the SamplePluginCpp sample plugin (obtainable from the KeePass plugins
page).
PLGX
Files
PLGX is an optional plugin file format for KeePass ≥ 2.09. Instead of compiling your plugin
to a DLL assembly, the plugin source code files can be packed into a PLGX
file and KeePass will compile the plugin itself when loading it.
The advantage of this approach is that plugins don't need to be recompiled
by the plugin developers
for each KeePass release anymore (as KeePass compiles the plugin itself, the generated plugin assembly
references the current, correct KeePass assembly). Instead of shipping a plugin
DLL assembly, you ship the PLGX.
For users, nothing changes. Instead of putting the plugin DLL assembly into
the KeePass application directory, the PLGX file needs to be put there.
Creating PLGX files.
PLGX files can be created from plugin sources by calling KeePass.exe
with the --plgx-create command line parameter. If you additionally
pass a path to the plugin sources directory (without terminating separator),
KeePass will use this one; otherwise
it'll show a folder browser dialog to allow you selecting the directory. If
you want to pass the directory location using the command line, make sure that
you're specifying a full, absolute path -- relative paths will not work.
In order to keep the size of the PLGX file small, it is recommended
that you clean up the plugin sources directory before compiling the PLGX.
Remove all unnecessary binary files (files in the bin
and obj directory); especially, delete any plugin assembly DLL
that you compiled yourself. Temporary files by the IDE
(like .suo and .user files)
can also be deleted.
PLGX features:
- Extensible, object-oriented file format.
- Compression support (data files are compressed using GZip).
.csproj support. KeePass retrieves all information required
for compiling the plugin assembly from the .csproj file in the
plugin sources.
- Embedded resources support.
- Referenced .NET assemblies support. References information is read from
the
.csproj file.
- Referenced custom assemblies support. Third-party assemblies required by the plugin
(references to DLLs) are supported, provided that the third-party assembly is
located in the plugin source code directory (or any subdirectory of it).
- ResX support.
.resx files are automatically compiled to
binary .resources files.
- .NET 3.5 support (if the default compiler, which is the one of .NET 2.0,
can't compile the code, KeePass tries using the .NET 3.5 compiler).
- PLGX cache. PLGX files are compiled once and the generated assembly is stored in a cache.
For all following KeePass starts, no compiling is required.
- PLGX cache maintenance. The size of the PLGX cache can be seen in the KeePass plugins dialog.
Here, the cache can also be marked to be cleared (it will be cleared when KeePass
is started the next time). An option to automatically delete old files from the
cache is supported and enabled by default.
PLGX limitations:
- Currently only C# is supported (not Visual Basic or any other .NET language).
- Linked resources (in different assemblies) are unsupported.
- Dependencies on other projects are unsupported (reorganize your project to
use custom assembly references instead).
Defining prerequisites. You can optionally specify a minimum
KeePass version, a minimum installed .NET Framework, an operating system and
the minimum size of a pointer (x86 vs. x64) using the
--plgx-prereq-kp:, --plgx-prereq-net:,
--plgx-prereq-os: and --plgx-prereq-ptr:
command line options. If one of the plugin prerequisites isn't met, KeePass shows a detailed
error message to the end-user (instead of a generic plugin incompatibility
message). Build example:
KeePass.exe --plgx-create C:\YourPluginDir --plgx-prereq-kp:2.09
--plgx-prereq-net:3.5
Valid operating system values are Windows and Unix.
When running on an unknown operating system, KeePass defaults to Windows.
Pointer sizes (checking for x86 vs. x64) are specified in bytes; for example,
to only allow running on x64, you specify --plgx-prereq-ptr:8.
Build commands. Optionally you can specify pre-build
and post-build commands using --plgx-build-pre: and
--plgx-build-post:. These commands are embedded in the PLGX file
and executed when compiling the plugin on the end-user's system.
In the build commands, the placeholder {PLGX_TEMP_DIR}
specifies the temporary directory (including a terminating separator),
to which the files were extracted. In the post-build command, {PLGX_CACHE_DIR}
is replaced by the cache directory of the plugin (including a terminating
separator), into which the generated assembly was stored.
These build commands can for example be used to copy additional files into
the cache directory. Example:
KeePass.exe --plgx-create C:\YourPluginDir
--plgx-build-post:"cmd /c COPY """{PLGX_TEMP_DIR}MyFile.txt"""
"""{PLGX_CACHE_DIR}MyFile.txt""""
In order to specify a quote character on the command line, it has
to be encoded using three quotes (this is Windows standard, see
MSDN: SHELLEXECUTEINFO). So, the command
line above will actually embed the post-build command
cmd /c COPY "{PLGX_TEMP_DIR}MyFile.txt"
"{PLGX_CACHE_DIR}MyFile.txt"
into the PLGX, which is correct.
It is highly recommended to surround paths including PLGX placeholders
using quotes, otherwise the command will not run correctly if the
path contains a space character (which happens very often).
If you need to run multiple commands, write them into a batch file and
execute it (with cmd). If you need to perform more complex
build tasks, write an own building executable and run it using the build
commands (typically it is useful to pass the directory locations as arguments
to your building executable), for example:
KeePass.exe --plgx-create C:\YourPluginDir
--plgx-build-post:"{PLGX_TEMP_DIR}MyBuild.exe {PLGX_TEMP_DIR} {PLGX_CACHE_DIR}"
|