Monday, April 5, 2010

Running an Interactive Application Through a Windows Service

Have a need to run an interactive application through a Windows Service?  I do and I did a LOT of searching on the Internet and the answer I found was that it can’t be done anymore ever since Windows Vista was released.

A lot of people on MSDN asked this question, but couldn’t seem to get it to work either.  I just assumed that it couldn’t be done since nobody else couldn’t get it to work either. 

Luckily, I asked this question myself on one of the MSDN forums and a MSFT moderator was able to point me to this blog: http://asprosys.blogspot.com/2009/03/allow-service-to-interact-with-desktop.html

Thankfully, Stephen Martin was able to get the problem solved and even has some sample code to show you that it does work as it should.  It’s in C#, but you can always translate it to VB if you need to.  I personally used a converter found here: http://dotnetspider.com/codeconvert/Default.aspx.  The converter isn’t perfect, but it only had a few things that needed to be fixed.

One issue I had though was with running a .cmd file (I imagine the same issue would happen for .com/.bat files also).  For some reason, running the CreateProcessAsUser would show the command window then disappear.  My .cmd file was a long file name with spaces so I thought maybe that had something to do with it.  I included double quotes around my command string like this:  cmd.exe /c “C:\This Is a Long Path\command.cmd”  The .cmd file would not run. 

Scratching my head, I put the above string in the Windows Run and tried to run it.  It wouldn’t run here either… I then tried putting the .cmd file in the root of my C:\ and tried running it like this: cmd.exe /c “C:\command.cmd”  This ran fine.  I figured that since both CreateProcessAsUser and Windows Run were having the same issue, it was a good thing. 

After much playing around with the string and a lot of frustration, I tried the following: cmd.exe /c “”C:\This Is a Long Path\command.cmd”  This worked… I’m not too sure why the double quotes are needed twice before the long file name though…  This also works with the .cmd file that was in the root of my C:\ like this: cmd.exe /c “”C:\command.cmd”