Click here to Skip to main content
11,929,939 members (52,786 online)
Click here to Skip to main content
Add your own
alternative version


111 bookmarked

How to Write a Terminal Services Add-in in Pure C#

, 31 May 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
A sample TS add-in written in C# (both server and client side)


Sometimes you need to write an extension to Terminal Services (if you have used it). So why don't you write it in your favorite programming language (for me, it's C#)?


Why am I playing with TS? How it started? Well ...

In our firm, almost everyone (about 120+) work on TS. We have a third party ERP system installed on our servers and there is an export function using Excel automation. Now is the question: how to use this functionality without spending money on two licenses for Excel for every user (that's right, in this case, all users should have license on both the server and the workstation)? The answer is: write an application which can provide the same (or at least what they are using) automation as Excel, and can build Excel files and send them to the client. The first version I wrote is based on exporting source-code from the ERP's producent (good to have friends there), and it was sending files via SMTP to the client, and it was written in ATL/WTL. But I knew the export source-code so I knew which object from Excel they (ERP's producent) were using.

After a few months, I found a way to send files over RDP. The application worked for more than a year. ... and then they changed the export code. After reading a great article about Building COM Servers in .NET, I decided to move this application to .NET. I found a way to get to know what functions/methods and objects they were using (IExpando from .NET and COM's IDispatchEx) and how to implement them. I thought, why not move the whole project to .NET, not just the server side. Well, I tried.

So back to the topic ... this article will not be about how to write Excel-like automation stuff. But how to write server/client side add-ins in C#.

What Should You Know?

What exactly will this sample application do?

The server side:

  • picks up a text file
  • reads it
  • compresses it using System.IO.Compression
  • sends it over RDP

The client side:

  • is ready for open RDP channels
  • opens it
  • reads data
  • decompresses
  • saves as text file
  • and opens it in the default application for the TXT extension

You'll find it useful when:

  • you know how to write such an extension in pure Win32 API
  • you want to write this in C#

Using the Code

Server Side

Well, it will be easy... all we have to do is import a few functions from wtsapi32.dll and use them in our application.

//The WTSVirtualChannelOpen function opens a handle
//to the server end of a specified virtual channel
HANDLE WTSVirtualChannelOpen(HANDLE hServer, DWORD SessionId,
                             LPSTR pVirtualName);

//The WTSVirtualChannelWrite function writes data
//to the server end of a virtual channel
BOOL WTSVirtualChannelWrite(HANDLE hChannelHandle, PCHAR Buffer,
                            ULONG Length, PULONG pBytesWritten);

//The WTSVirtualChannelClose function closes an open virtual channel handle.
BOOL WTSVirtualChannelClose(HANDLE hChannelHandle);

In C#, they look like this:

using System;
using System.Runtime.InteropServices;

class WtsApi32
    public static extern IntPtr WTSVirtualChannelOpen(IntPtr server,
        int sessionId, [MarshalAs(UnmanagedType.LPStr)] string virtualName);

    [DllImport("Wtsapi32.dll", SetLastError = true)]
    public static extern bool WTSVirtualChannelWrite(IntPtr channelHandle,
           byte[] buffer, int length, ref int bytesWritten);

    [DllImport("Wtsapi32.dll", SetLastError = true)]
    public static extern bool WTSVirtualChannelRead(IntPtr channelHandle,
           byte[] buffer, int length, ref int bytesReaded);

    public static extern bool WTSVirtualChannelClose(IntPtr channelHandle);

Now sending the data:

byte[] data = PseudoClass.GetSomeData();
//remember that VirtualName should have 7 or less signs

IntPtr mHandle = WtsApi32.WTSVirtualChannelOpen(IntPtr.Zero, -1, "TSCS");
int written = 0;
bool ret = WtsApi32.WTSVirtualChannelWrite(mHandle, data,
           data.Length, ref written);
if (!ret || written == gziped.Length)
    MessageBox.Show("Sent!", "OK", MessageBoxButtons.OK,
    MessageBox.Show("Bumm! Somethings gone wrong!", "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
ret = WtsApi32.WTSVirtualChannelClose(mHandle);

Off we go ... data sent (well, only when we correct the setup client-side stuff).

Client Side

What sits on the client side? Well, the client side is a DLL which exports a function in the first place in the export table.


We will also need a definition for this:

typedef struct tagCHANNEL_ENTRY_POINTS {
  DWORD cbSize;
  DWORD protocolVersion;

  LPVOID FAR * ppInitHandle,
  PCHANNEL_DEF pChannel,
  INT channelCount,
  ULONG versionRequested,
  PCHANNEL_INIT_EVENT_FN pChannelInitEventProc

UINT VCAPITYPE VirtualChannelOpen(
  LPVOID pInitHandle,
  LPDWORD pOpenHandle,
  PCHAR pChannelName,
  PCHANNEL_OPEN_EVENT_FN pChannelOpenEventProc

UINT VCAPITYPE VirtualChannelClose(
  DWORD openHandle

UINT VCAPITYPE VirtualChannelWrite(
  DWORD openHandle,
  LPVOID pData,
  ULONG dataLength,
  LPVOID pUserData

OMG!!! pointer to functions.. it doesn't look good. Well, maybe, but delegates from .NET are actually functions pointers, so ... we will try to wrap all this stuff into some class.

using System;
using System.Drawing;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Text;
using System.Threading;

namespace Win32
    namespace WtsApi32
        public delegate ChannelReturnCodes
            VirtualChannelInitDelegate(ref IntPtr initHandle,
            ChannelDef[] channels, int channelCount, int versionRequested,
            ChannelInitEventDelegate channelInitEventProc);
        public delegate ChannelReturnCodes
            VirtualChannelOpenDelegate(IntPtr initHandle, ref int openHandle,
            [MarshalAs(UnmanagedType.LPStr)] string channelName,
            ChannelOpenEventDelegate channelOpenEventProc);
        public delegate ChannelReturnCodes
            VirtualChannelCloseDelegate(int openHandle);
        public delegate ChannelReturnCodes
            VirtualChannelWriteDelegate(int openHandle, byte[] data,
            uint dataLength, IntPtr userData);

        public delegate void ChannelInitEventDelegate(IntPtr initHandle,
            ChannelEvents Event,
            [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)]
            byte[] data, int dataLength);
        public delegate void ChannelOpenEventDelegate(int openHandle,
            ChannelEvents Event,
            [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] data,
            int dataLength, uint totalLength, ChannelFlags dataFlags);

        public struct ChannelEntryPoints
            public int Size;
            public int ProtocolVersion;
            public VirtualChannelInitDelegate VirtualChannelInit;
            public VirtualChannelOpenDelegate VirtualChannelOpen;
            public VirtualChannelCloseDelegate VirtualChannelClose;
            public VirtualChannelWriteDelegate VirtualChannelWrite;

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
        public struct ChannelDef
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
            public string name;
            public ChannelOptions options;

        public enum ChannelEvents
            Initialized = 0,
            Connected = 1,
            V1Connected = 2,
            Disconnected = 3,
            Terminated = 4,
            DataRecived = 10,
            WriteComplete = 11,
            WriteCanceled = 12

        public enum ChannelFlags
            First = 0x01,
            Last = 0x02,
            Only = First | Last,
            Middle = 0,
            Fail = 0x100,
            ShowProtocol = 0x10,
            Suspend = 0x20,
            Resume = 0x40

        public enum ChannelOptions : uint
            Initialized = 0x80000000,
            EncryptRDP = 0x40000000,
            EncryptSC = 0x20000000,
            EncryptCS = 0x10000000,
            PriorityHigh = 0x08000000,
            PriorityMedium = 0x04000000,
            PriorityLow = 0x02000000,
            CompressRDP = 0x00800000,
            Compress = 0x00400000,
            ShowProtocol = 0x00200000

        public enum ChannelReturnCodes
            Ok = 0,
            AlreadyInitialized = 1,
            NotInitialized = 2,
            AlreadyConnected = 3,
            NotConnected = 4,
            TooManyChanels = 5,
            BadChannel = 6,
            BadChannelHandle = 7,
            NoBuffer = 8,
            BadInitHandle = 9,
            NotOpen = 10,
            BadProc = 11,
            NoMemory = 12,
            UnknownChannelName = 13,
            AlreadyOpen = 14,
            NotInVirtualchannelEntry = 15,
            NullData = 16,
            ZeroLength = 17

OK. I wasn't so bad. Now, how simple does the RDP client side DLL look in C/C++:

LPHANDLE              gphChannel;
DWORD                 gdwOpenChannel;

void WINAPI VirtualChannelOpenEvent(DWORD openHandle,
     UINT event, LPVOID pdata,
     UINT32 dataLength, UINT32 totalLength,
     UINT32 dataFlags)
        //reading data... and reading ... and reading


VOID VCAPITYPE VirtualChannelInitEventProc(LPVOID pInitHandle, UINT event,
                                           LPVOID pData, UINT dataLength)
    UINT  ui;
            ui = gpEntryPoints->pVirtualChannelOpen(
                "SAMPLE", (PCHANNEL_OPEN_EVENT_FN)VirtualChannelOpenEvent);
            if (ui != CHANNEL_RC_OK)
                MessageBox(NULL,TEXT("Open of RDP virtual "
                          "channel failed"),TEXT("Sample App"),MB_OK);
            MessageBox(NULL,TEXT("Connecting to a non Windows 2000 "
                      "Terminal Server"), TEXT("Sample App"),MB_OK);

    UINT        uRet;
    gpEntryPoints = (PCHANNEL_ENTRY_POINTS) LocalAlloc(LPTR,
    CopyMemory(gpEntryPoints, pEntryPoints, pEntryPoints->cbSize);
    ZeroMemory(&cd, sizeof(CHANNEL_DEF));
    CopyMemory(, "SAMPLE", 6);
    uRet = gpEntryPoints->pVirtualChannelInit((LPVOID *)&gphChannel,
    if (uRet != CHANNEL_RC_OK)
        MessageBox(NULL,TEXT("RDP Virtual channel Init Failed"),
                        TEXT("Sample App"),MB_OK);
        return FALSE;
    if (cd.options != CHANNEL_OPTION_INITIALIZED)
        return FALSE;
    return TRUE;

After translation to C#:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Win32.WtsApi32;

namespace TSAddinInCS
    public class TSAddinInCS
        static IntPtr Channel;
        static ChannelEntryPoints entryPoints;
        static int OpenChannel = 0;
        //ATTENTION: name should have 7 or less signs
        const string ChannelName = "TSCS";
        static Unpacker unpacker = null;
        static ChannelInitEventDelegate channelInitEventDelegate =
            new ChannelInitEventDelegate(VirtualChannelInitEventProc);
        static ChannelOpenEventDelegate channelOpenEventDelegate =
            new ChannelOpenEventDelegate(VirtualChannelOpenEvent);

        public static bool VirtualChannelEntry(ref ChannelEntryPoints entry)
            ChannelDef[] cd = new ChannelDef[1];
            cd[0] = new ChannelDef();
            entryPoints = entry;
            cd[0].name = ChannelName;
            ChannelReturnCodes ret = entryPoints.VirtualChannelInit(
                ref Channel, cd, 1, 1, channelInitEventDelegate);
            if (ret != ChannelReturnCodes.Ok)
                MessageBox.Show("TSAddinInCS: RDP Virtual channel"
                                " Init Failed.\n" + ret.ToString(),
                                "Error", MessageBoxButtons.OK,
                return false;
            return true;

        public static void VirtualChannelInitEventProc(IntPtr initHandle,
            ChannelEvents Event, byte[] data, int dataLength)
            switch (Event)
                case ChannelEvents.Initialized:
                case ChannelEvents.Connected:
                    ChannelReturnCodes ret = entryPoints.VirtualChannelOpen(
                        initHandle, ref OpenChannel,
                        ChannelName, channelOpenEventDelegate);
                    if (ret != ChannelReturnCodes.Ok)
                        MessageBox.Show("TSAddinInCS: Open of RDP " +
                            "virtual channel failed.\n" + ret.ToString(),
                            "Error", MessageBoxButtons.OK,
                        string servername = System.Text.Encoding.Unicode.GetString(data);
                        servername = servername.Substring(0, servername.IndexOf('\0'));
                        //do something with server name
                case ChannelEvents.V1Connected:
                    MessageBox.Show("TSAddinInCS: Connecting" +
                        " to a non Windows 2000 Terminal Server.",
                        "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                case ChannelEvents.Disconnected:
                case ChannelEvents.Terminated:

        public static void VirtualChannelOpenEvent(int openHandle,
            ChannelEvents Event, byte[] data,
            int dataLength, uint totalLength, ChannelFlags dataFlags)
            switch (Event)
                case ChannelEvents.DataRecived:
                    switch (dataFlags & ChannelFlags.Only)
                        case ChannelFlags.Only:
                            //we are here because first data is last too
                            //(totalLength == dataLength)
                            // something with data
                        case ChannelFlags.First:
                            //first part of data arrived
                            // something with data
                            //(store 'coz it isn't all)
                        case ChannelFlags.Middle:
                            //...and still arriving
                            // something with data
                            //(store 'coz it isn't all)
                        case ChannelFlags.Last:
                            //...and still arriving
                            //well maybe not still this is the last part
                            // something with data (store)
                            //now we have full data in store
                            //we will do with it something more than storing

Is That All?

(Isn't that a name of a U2 song? Actually - No.. We didn't export the function ... or did we?


What does it mean? Well, I have a tool which can help with exporting functions to unmanaged code. You can read about it here. This tool is also included in the source (as a binary) and "added to post-build actions".

How To Get It All To Work

OK, now we have all pieces. The sample solution has two projects, the server and the client side and the ExportDLL tool, But it won't work, hrhrhrhr. We need to set it up first. What exactly do we need to run this:

  • A server (well, it can be Windows XP) working as the terminal server
  • A workstation with a TS client (mstsc.exe)

We also need the following files:

  • TSAddinInCS.dll on the workstation
  • TSAddinInCSServer.exe on the server


Setting up the client (the server doesn't need setup) is easy:

  • Open regedit
  • Find HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client\Default\AddIns
  • Add a key TSAddinInCS
  • Add a key with a new string named Name to that key
  • Change the value of this string to whole_path_to\TSAddinInCS.dll

Or just make a *.reg file with:

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\Terminal Server
"Name"="C:\\Documents and Settings\\Selvin\\Pulpit\\TSAddinInCS

This changes C:\\Documents and Settings\\Selvin\\Pulpit\\TSAddinInCS\\Client\\bin\\Debug\\ to the proper path.


Finally, we have to test it. Run mstsc.exe, connect to the server, run TSAddinInCSServer.exe on the server, hit the button, choose the file to send, and watch as this file opens on the local computer.


To Do List

  • Add sending files to server description

Tips & Tricks/Notes

Many people ask why mstsc.exe crashes when they are sending data to the server.

The answer lies in very small read buffers on the server side.

From MSDN:

    Specifies the size, in bytes, of Buffer.
    If the client set the CHANNEL_OPTION_SHOW_PROTOCOL option,
    the value of this parameter should be at least CHANNEL_PDU_LENGTH.
    If the CHANNEL_OPTION_SHOW_PROTOCOL is not used, the value of this
    parameter should be at least CHANNEL_CHUNK_LENGTH.

CHANNEL_CHUNK_LENGTH is defined as 1600.


  • 14-11-2006: First version
  • 30-05-2008: Second version
    • IntPtr data changed to byte[] data
    • GC.KeepAlive() added
    • Sending files to server added (in source)
    • Sample form and tray icon added (in source)


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Systems / Hardware Administrator
Poland Poland
No Biography provided

You may also be interested in...

Comments and Discussions

QuestionName of Server where we are connecting? Pin
kalpeshmjoshi24-Sep-15 21:29
memberkalpeshmjoshi24-Sep-15 21:29 
QuestionFOR Remote Apps Pin
geo_rge121230-Aug-13 4:48
membergeo_rge121230-Aug-13 4:48 
QuestionDeployed Application on Server and Client Side, but it is not working Pin
V Mohan Rao16-Jul-13 2:54
memberV Mohan Rao16-Jul-13 2:54 
AnswerRe: Deployed Application on Server and Client Side, but it is not working Pin
ggparti17-Oct-13 2:16
memberggparti17-Oct-13 2:16 
GeneralRe: Deployed Application on Server and Client Side, but it is not working Pin
Selvin8-Nov-13 17:57
memberSelvin8-Nov-13 17:57 
QuestionExportDLL problems from the command line Pin
NightShade4217-Jan-13 3:11
memberNightShade4217-Jan-13 3:11 
AnswerRe: ExportDLL problems from the command line Pin
NightShade4217-Jan-13 8:16
memberNightShade4217-Jan-13 8:16 
QuestionRDS installation Pin
l33tuser8-Jan-13 3:31
memberl33tuser8-Jan-13 3:31 
GeneralMy vote of 5 Pin
Member 82062131-Jan-13 21:06
memberMember 82062131-Jan-13 21:06 
Questionx64 Issue Pin
Genesis Emberga5-Nov-12 17:03
memberGenesis Emberga5-Nov-12 17:03 
AnswerRe: x64 Issue Pin
Genesis Emberga7-Nov-12 16:49
memberGenesis Emberga7-Nov-12 16:49 
GeneralRe: x64 Issue Pin
little_MASTER20-Oct-14 21:47
memberlittle_MASTER20-Oct-14 21:47 
QuestionAdding another DLL to the Client side project Pin
Nitin Parulekar17-Nov-11 18:03
memberNitin Parulekar17-Nov-11 18:03 
AnswerRe: Adding another DLL to the Client side project Pin
Selvin17-Nov-11 22:10
memberSelvin17-Nov-11 22:10 
GeneralRe: Adding another DLL to the Client side project Pin
Nitin Parulekar20-Nov-11 10:29
memberNitin Parulekar20-Nov-11 10:29 
QuestionCitrix virual channel in c# Pin
peroziu18-Aug-11 2:19
memberperoziu18-Aug-11 2:19 
QuestionMissing Data Pin
I like pudding11-Aug-11 14:17
memberI like pudding11-Aug-11 14:17 
AnswerRe: Missing Data Pin
Selvin11-Aug-11 21:55
memberSelvin11-Aug-11 21:55 
GeneralRe: Missing Data Pin
I like pudding12-Aug-11 2:52
memberI like pudding12-Aug-11 2:52 
GeneralRe: Missing Data Pin
I like pudding24-Aug-11 9:49
memberI like pudding24-Aug-11 9:49 
GeneralNothing happens on the client Pin
tritter22-Feb-11 8:52
membertritter22-Feb-11 8:52 
GeneralRe: Nothing happens on the client Pin
Selvin22-Feb-11 23:52
memberSelvin22-Feb-11 23:52 
GeneralCan't build from source Pin
mrbill08-Dec-10 8:45
membermrbill08-Dec-10 8:45 
GeneralRe: Can't build from source Pin
Selvin9-Dec-10 3:20
memberSelvin9-Dec-10 3:20 
GeneralRe: Can't build from source Pin
mrbill010-Dec-10 5:42
membermrbill010-Dec-10 5:42 
GeneralRe: Can't build from source Pin
Selvin10-Dec-10 6:25
memberSelvin10-Dec-10 6:25 
GeneralRe: Can't build from source Pin
mrbill010-Dec-10 11:24
membermrbill010-Dec-10 11:24 
GeneralDesign Pin
mrbill01-Dec-10 9:04
membermrbill01-Dec-10 9:04 
GeneralRe: Design Pin
Selvin1-Dec-10 10:33
memberSelvin1-Dec-10 10:33 
NewsRDPAddins .NET on Pin
Selvin20-Nov-10 9:16
memberSelvin20-Nov-10 9:16 
QuestionHow to register client-side for All Users? Pin
Hintz20-Sep-10 11:08
memberHintz20-Sep-10 11:08 
AnswerRe: How to register client-side for All Users? Pin
Selvin20-Sep-10 12:02
memberSelvin20-Sep-10 12:02 
GeneralNew project - RDPAddins Pin
Selvin14-Sep-10 2:38
memberSelvin14-Sep-10 2:38 
GeneralRe: New project - RDPAddins Pin
mrbill017-Nov-10 9:55
membermrbill017-Nov-10 9:55 
GeneralRe: New project - RDPAddins [modified] Pin
Selvin18-Nov-10 6:31
memberSelvin18-Nov-10 6:31 
GeneralRe: New project - RDPAddins Pin
mrbill018-Nov-10 6:54
membermrbill018-Nov-10 6:54 
GeneralRe: New project - RDPAddins Pin
Selvin18-Nov-10 6:59
memberSelvin18-Nov-10 6:59 
QuestionError when sending directly after reading Pin
xarfai9-Sep-10 4:36
memberxarfai9-Sep-10 4:36 
AnswerRe: Error when sending directly after reading [modified] Pin
Selvin14-Sep-10 2:16
memberSelvin14-Sep-10 2:16 
GeneralExportDll source code Pin
ta-ale18-Jul-10 23:27
memberta-ale18-Jul-10 23:27 
GeneralRe: ExportDll source code Pin
Selvin19-Jul-10 4:25
memberSelvin19-Jul-10 4:25 
GeneralRe: ExportDll source code Pin
ta-ale19-Jul-10 5:18
memberta-ale19-Jul-10 5:18 
GeneralRe: ExportDll source code Pin
Selvin19-Jul-10 23:52
memberSelvin19-Jul-10 23:52 
GeneralRe: ExportDll source code Pin
ta-ale22-Jul-10 4:28
memberta-ale22-Jul-10 4:28 
GeneralRe: ExportDll source code Pin
Selvin25-Jul-10 23:29
memberSelvin25-Jul-10 23:29 
GeneralRe: ExportDll source code Pin
ta-ale19-Jul-10 22:39
memberta-ale19-Jul-10 22:39 
GeneralRe: ExportDll source code Pin
I like pudding8-Aug-11 4:24
memberI like pudding8-Aug-11 4:24 
GeneralRe: ExportDll source code Pin
Selvin8-Aug-11 4:33
memberSelvin8-Aug-11 4:33 
GeneralRe: ExportDll source code Pin
I like pudding8-Aug-11 9:07
memberI like pudding8-Aug-11 9:07 
GeneralRe: ExportDll source code Pin
Selvin8-Aug-11 21:53
memberSelvin8-Aug-11 21:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.151126.1 | Last Updated 31 May 2008
Article Copyright 2006 by Selvin
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid