How to add a Custom Action C# to WIX Installer

In this example, I will show how to create a Custom Action C# project, and add the function to the Wix source of the Wix project in Visual Studio. This is a Wix custom action example when the function is defined in C# and added to the installation sequence that will be a part of the Windows MSI Package.

Create a C# Custom Action Project

In this example, a C# CustomAction project was created by choosing a template in Visual Studio. This custom action project in C# will generate a dynamic linked library file (DLL) as an output.

The custom action function here is EndProcesses which will be an entry point to CustomAction defined in Wix.

using Microsoft.Deployment.WindowsInstaller;
using System.Diagnostics;

namespace Setup
{
    public class CustomActions
    {
        [CustomAction]
        public static ActionResult EndProcesses(Session session)
        {
            session.Log("Begin CustomAction");

            string[] processNames = { "winword", "notepad" };

            foreach (string pn in processNames)
            {
                EndProcessByName(pn);
            }
            return ActionResult.Success;
        }

        private static void EndProcessByName(string pName)
        {
            foreach (Process p in Process.GetProcessesByName(pName))
            {
                p.Kill();
            }
        }
    }
}

Run:

Setup.CA.dll is the one to be added to Wix as the source file of Binary.

.CA is MakeSfxCA packaged single dll output appending reference dlls (ex. Microsoft.Deployment.WindowsInstaller.dll) in addition to project output, setup.dll.

Define The CustomAction Binary with Source File

The project final packed dll will be used as a Source file for CustomAction Binary in wxs definition.

<Binary Id="CustomActionBinary" SourceFile="..\CustomActions\Setup\bin\Release\Setup.CA.dll" />    

Define Custom Action with Function DllEntry

Add CustomAction in Wix definition using BinaryKey and DllEntry for the CA function.

<CustomAction 
          Id="CustomActionEndProcesses" 
          BinaryKey="CustomActionBinary" 
          Impersonate="yes" Execute='immediate' DllEntry="EndProcesses" Return="check"
/>

Add the CustomAction into InstallExecuteSequence

The execution of the custom action was added to InstallExecuteSequence with Tag, Custom.

<InstallExecuteSequence>

   <Custom Action='CustomActionEndProcesses' Before='InstallInitialize'>NOT Installed</Custom>
    
</InstallExecuteSequence>

Build the wix custom action example

msbuild simple.wixproj /t:Build /p:Configuration=Release

Run:

When running this MSI, you can see any defined running processes closed by the custom action.

You may be interested in reading other articles:

How to run PowerShell script with WIX Custom Action

How to add a Custom Dialog in Wix Installer

Leave a Comment