Link to home
Start Free TrialLog in
Avatar of LeighWardle
LeighWardleFlag for Australia

asked on

How to detect if a running Windows application is being accessed remotely?

Hi Experts,

I am looking for a way to detect if my running vb.net Windows Forms application is being accessed remotely via software such as Remote Desktop, VNC, Teamviewer etc.

Regards,
Leigh
Avatar of chaau
chaau
Flag of Australia image

There is a Win32 API that is designed for this:
GetSystemMetrics(SM_REMOTESESSION);

Open in new window

When the program running in a remote desktop session the API will return not zero value.
Please check this web-site how to call this API via PInvoke:
Public Declare Auto Function GetSystemMetrics Lib "user32.dll" (ByVal smIndex As Integer) As Integer

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of SAMIR BHOGAYTA
SAMIR BHOGAYTA
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of LeighWardle

ASKER

Hi samirbhogayta,  thanks for your suggestion.

I am not a c## developer, so I converted your code to vb.net:

Imports System.Runtime.InteropServices

Public Class RemoteSessionChecker
	''' <summary>
	''' Checks whether the current user is is logged in through a remote session
	''' </summary>
	''' <returns></returns>
	Public Shared Function Check() As Boolean
		Dim IsRemoteSession As Boolean = False
		'Constant used to check for remote sessions
		Const  SM_REMOTESESSION As Integer = &H2001
		'This function will return 0 if the session is local
		Dim Value As Integer = GetSystemMetrics(SM_REMOTESESSION)

		IsRemoteSession = (Value <> 0)

		Return IsRemoteSession
	End Function

	<DllImport("user32.dll", EntryPoint := ("GetSystemMetrics"))> _
	Private Shared Function GetSystemMetrics(nIndex As Integer) As Integer
	End Function
End Class

'=======================================================
'Service provided by Telerik (www.telerik.com)
'Conversion powered by NRefactory.
'Twitter: @telerik
'Facebook: facebook.com/telerik
'=======================================================

Open in new window


But the function always returns False - even when I am connected by RDP.

Regards,
Leigh
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks, chaau.

Changing SM_REMOTESESSION value (for VB) to &H1000 now makes the code detect if it is connected by RDP.
That's the good news.

The bad news is that it does not detect if it is connected via TeamViewer.  (I haven't tried VNC or anything else).
Teamviewer, Logmein and such technically do not work via RDP, but connect to the user session. They cannot be detected via SM_REMOTESESSION. You will need to test if processes associated with these services are running using CreateToolhelp32Snapshot() API.