views:

1060

answers:

4

In Windows Server 2003, how I can check if my program is running in local console ("on the screen of the server machine") instead of remote session?

I'm using Delphi Win32, so any Windows API based method should work..

+1  A: 

Wouldn't the session number tell you this ?

ProcessIdToSessionId (GetCurrentProcessId(),&dwSessionNum)

You'd have to check the OS version as well, using GetVersionEx: for everything up to XP/Server 2003 session 0 is local (service or interactive console), anything higher is virtual. For Vista/2008 session 0 and 1 are both local (0 is service, 1 is console), everything else is virtual.

I'm guessing your Delphi units would declare the session number as var, so you wouldn't need the ampersand.

Bob Moore
I THINK that all interactive sessions, local or remote, are going to be > 0 in the not to distant future.
jms
Currently this method will do..
Harriv
One note: session 0 can still be used remotely via "mstsc /console". WTSGetActiveConsoleSessionID and WTSQuerySessionInformation should help if you need to identify this as well.
DK
mstsc /console is now known as mstsc /admin
Adam Mitz
I found also this method later from about.com: http://delphi.about.com/od/delphitips2008/qt/isremotesession.htm
Harriv
+1  A: 

WTSGetActiveConsoleSessionId() should return the ID of the session attached to the console. You can then compare that session id with your application's current session ID to determine whether you are running on the console or not. Vista (not sure about Windows Server 2008) does not necessarily give the console session the ID of 1 (Fast User Switching, anyone?).

Brian
Anders - your technique won't work on Windows 2008 or Vista. Windows 2008 and Vista use Session 0 isolation which means that only system processes and services run in session 0. An interactive session, whether it be via RDP or not, will by definition NOT be 0:http://msdn.microsoft.com/en-us/library/bb756986.aspx
Brian
A: 

Brian is correct, I have since encountered Vista reporting a session id of 2 for an interactive console, despite the fact that Fast User Switching was not in use. Of course, this may be just be a bug :-)

Bob Moore
+1  A: 

For me, ProcessIdToSessionId returned 0 both when run directly at the physical console and when logged in to the administrative session (mstsc /admin).

However, when you login via RDP, Windows (XP Pro in this case) creates a new session which it shows on the physical console which just has the "this computer is locked" display. WTSGetActiveConsoleSessionId returns the session id for that second session which in my case was 2.

So even though your app is running on the console, there are now two console sessions and your app is not running on the active one. In my code I compare session id against 0 instead.

Anders Öhrt