C++: check if computer is locked - c++

I'm trying to figure out whether the computer is locked.
I've looked at LockWorkStation function, but the function that I'm hoping to find is IsWorkStationLocked.
I need to support all windows version >= XP

For windows 7 and abowe WTS API can be used:
bool IsSessionLocked() {
typedef BOOL (PASCAL * WTSQuerySessionInformation)(HANDLE hServer, DWORD SessionId, WTS_INFO_CLASS WTSInfoClass, LPTSTR* ppBuffer, DWORD* pBytesReturned);
typedef void (PASCAL * WTSFreeMemory)( PVOID pMemory);
WTSINFOEXW * pInfo = NULL;
WTS_INFO_CLASS wtsic = DW_WTSSessionInfoEx;
bool bRet = false;
LPTSTR ppBuffer = NULL;
DWORD dwBytesReturned = 0;
LONG dwFlags = 0;
WTSQuerySessionInformation pWTSQuerySessionInformation = NULL;
WTSFreeMemory pWTSFreeMemory = NULL;
HMODULE hLib = LoadLibrary( _T("wtsapi32.dll") );
if (!hLib) {
return false;
}
pWTSQuerySessionInformation = (WTSQuerySessionInformation)GetProcAddress(hLib, "WTSQuerySessionInformationW" );
if (!pWTSQuerySessionInformation) {
goto EXIT;
}
pWTSFreeMemory = (WTSFreeMemory)GetProcAddress(hLib, "WTSFreeMemory" );
if (pWTSFreeMemory == NULL) {
goto EXIT;
}
if(pWTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, g_dwSessionID, wtsic, &ppBuffer, &dwBytesReturned)) {
if(dwBytesReturned > 0) {
pInfo = (WTSINFOEXW*)ppBuffer;
if (pInfo->Level == 1) {
dwFlags = pInfo->Data.WTSInfoExLevel1.SessionFlags;
}
if (dwFlags == WTS_SESSIONSTATE_LOCK) {
bRet = true;
}
}
pWTSFreeMemory(ppBuffer);
ppBuffer = NULL;
}
EXIT:
if (hLib != NULL) {
FreeLibrary(hLib);
}
return bRet;
}
Please check following article for supported platforms for WTSINFOEX structure:
https://technet.microsoft.com/ru-ru/sysinternals/ee621017

From the same MSDN link you gave, the third paragraph of "Remarks" says:
This function has the same result as pressing Ctrl+Alt+Del and clicking Lock Workstation. To unlock the workstation, the user must log in. There is no function you can call to determine whether the workstation is locked. To receive notification when the user logs in, use the WTSRegisterSessionNotification function to receive WM_WTSSESSION_CHANGE messages. You can use session notifications to track the desktop state so you know whether it is possible to interact with the user.

Alex Vershynin's version works well, with a few code changes that I had to make.
I had to: change DW_WTSSessionInfoEx to WTSSessionInfoEx (Answering user586399), define "g_dwSessionID" to WTSGetActiveConsoleSessionId(), include Wtsapi32.h. I think that's it ...
Since I can't comment, I'll paste the whole code here.
#include "Wtsapi32.h"
bool IsSessionLocked()
{
typedef BOOL( PASCAL * WTSQuerySessionInformation )( HANDLE hServer, DWORD SessionId, WTS_INFO_CLASS WTSInfoClass, LPTSTR* ppBuffer, DWORD* pBytesReturned );
typedef void ( PASCAL * WTSFreeMemory )( PVOID pMemory );
WTSINFOEXW * pInfo = NULL;
WTS_INFO_CLASS wtsic = WTSSessionInfoEx;
bool bRet = false;
LPTSTR ppBuffer = NULL;
DWORD dwBytesReturned = 0;
LONG dwFlags = 0;
WTSQuerySessionInformation pWTSQuerySessionInformation = NULL;
WTSFreeMemory pWTSFreeMemory = NULL;
HMODULE hLib = LoadLibrary( "wtsapi32.dll" );
if( !hLib )
{
return false;
}
pWTSQuerySessionInformation = (WTSQuerySessionInformation) GetProcAddress( hLib, "WTSQuerySessionInformationW" );
if( pWTSQuerySessionInformation )
{
pWTSFreeMemory = (WTSFreeMemory) GetProcAddress( hLib, "WTSFreeMemory" );
if( pWTSFreeMemory != NULL )
{
DWORD dwSessionID = WTSGetActiveConsoleSessionId();
if( pWTSQuerySessionInformation( WTS_CURRENT_SERVER_HANDLE, dwSessionID, wtsic, &ppBuffer, &dwBytesReturned ) )
{
if( dwBytesReturned > 0 )
{
pInfo = (WTSINFOEXW*) ppBuffer;
if( pInfo->Level == 1 )
{
dwFlags = pInfo->Data.WTSInfoExLevel1.SessionFlags;
}
if( dwFlags == WTS_SESSIONSTATE_LOCK )
{
bRet = true;
}
}
pWTSFreeMemory( ppBuffer );
ppBuffer = NULL;
}
}
}
if( hLib != NULL )
{
FreeLibrary( hLib );
}
return bRet;
}

Just as a refinement to MGamsby's post: if you are targeting the Win8.1 SDK or Win10 SDK, then it's not necessary to mess around with GetProcAddress(), LoadLibrary(), and WTSGetActiveConsoleSessionId(), and the code becomes much more compact:
bool isSessionLocked()
{
WTSINFOEXW* pInfo = NULL;
WTS_INFO_CLASS wtsic = WTSSessionInfoEx;
LPTSTR ppBuffer = NULL;
DWORD dwBytesReturned = 0;
LONG sessionFlags = WTS_SESSIONSTATE_UNKNOWN; // until we know otherwise. Prevents a false positive since WTS_SESSIONSTATE_LOCK == 0
DWORD dwSessionID = WTSGetActiveConsoleSessionId();
if (WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, dwSessionID, wtsic, &ppBuffer, &dwBytesReturned))
{
if (dwBytesReturned > 0)
{
pInfo = (WTSINFOEXW*)ppBuffer;
if (pInfo->Level == 1)
{
sessionFlags = pInfo->Data.WTSInfoExLevel1.SessionFlags;
}
}
WTSFreeMemory(ppBuffer);
ppBuffer = NULL;
}
return (sessionFlags == WTS_SESSIONSTATE_LOCK);
}
NOTE:
I realise that the question is about Windows 7 but you can still target Win7 using the Win8.1 SDK, and it is available for use in VS2015 onwards.
Edit: Oops. I just realised the OP asked for WinXP onwards in which case, yes, you do need to mess around with LoadLibrary() etc. Sorry about that.
I'll leave my code here in case it is useful for anyone.

Apparently there is a difference between screen lock and session lock. Here're my investigations results.
A session becomes locked when a password box is shown on the lock screen. In Windows 7 after pressing Win+L lockscreen appears with password box, so a session is locked immediately. But in Win10/11 lockscreen initially appears without password box. And nothing happens. After pressing a key or clicking a mouse button, password box appears and session becomes locked.
WTSRegisterSessionNotification(): WM_WTSSESSION_CHANGE message arrives after password box is shown.
WTSQuerySessionInformation(): sessionFlags == WTS_SESSIONSTATE_LOCK after password box is shown
SetWinEventHook() with EVENT_SYSTEM_DESKTOPSWITCH: multiple events arrives when (un)locking. Looks like two desktops are created when locking: for initial lock screen and the one with password box.
SwitchDesktop() succeeds until password box is shown.
Checking for running LogonUI.exe works, but it remains running for a while after unlock. Theoretically in the future versions it may remain running permanently. So one can't be absolutely sure the session is locked if LogonUI.exe is running.
So far I haven't found a reliable way to check if computer is locked and unlocked. But I'll try to continue my research.

Related

How to run functions from a service in current logged in users context using C++?

currently I have 1 main function which calls 3-4 utility functions that collectively block other browsers using Windows Registry and implements a firefox policy using mkdir + copy, currently, these functions aren't running under users context and are running under the system, My codebase has the function to run a cmd command under user's context but not other functions, below I have mentioned it. I am guessing running the main function under other user's contexts will automatically run the utility functions also under the user's context, since the main function calls the utility functions but I am not sure, anybody knows how to do this, the function basically first creates a directory and copy a file to it in Program Files folder and then get paths of browsers and create & set Registry keys and data-values for that user, but currently due to running from service it runs under SYSTEM.
BOOLEAN
CreateProcessInActiveSession(
const std::wstring wstrCmd
)
{
DWORD dwSId = 0xFFFFFFFF;
dwSId = WTSGetActiveConsoleSessionId();// LZGetActiveSessionId();
if (0xFFFFFFFF == dwSId)
{
return FALSE;
}
BOOL bRet;
HANDLE hTok = NULL;
bRet = WTSQueryUserToken(dwSId, &hTok);
if (FALSE == bRet)
{
return FALSE;
}
DWORD dwLinkedTokSz;
TOKEN_LINKED_TOKEN ElvTok;
bRet = GetTokenInformation(hTok, TokenLinkedToken, &ElvTok, sizeof(ElvTok), &dwLinkedTokSz);
if (TRUE == bRet)
{
CloseHandle(hTok);
hTok = ElvTok.LinkedToken;
}
HANDLE hTokDup = NULL;
bRet = DuplicateTokenEx(hTok, MAXIMUM_ALLOWED, NULL, SecurityIdentification, TokenPrimary, &hTokDup);
if (FALSE == bRet)
{
CloseHandle(hTok);
return FALSE;
}
CloseHandle(hTok);
DWORD dwCreationFlag;
dwCreationFlag = NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE;
PVOID pEnv = NULL;
bRet = CreateEnvironmentBlock(&pEnv, hTokDup, FALSE);
if (FALSE == bRet)
{
pEnv = NULL;
}
else
{
dwCreationFlag |= CREATE_UNICODE_ENVIRONMENT;
}
STARTUPINFO stInfo;
memset(&stInfo, 0, sizeof(stInfo));
PROCESS_INFORMATION procInfo;
memset(&procInfo, 0, sizeof(procInfo));
stInfo.cb = sizeof(stInfo);
WCHAR szDesktop[] = L"winsta0\\default";
stInfo.lpDesktop = szDesktop;
WCHAR wszCmd[MAX_PATH];
wcscpy_s(wszCmd, ARRAY_SIZE(wszCmd), wstrCmd.c_str());
bRet = CreateProcessAsUserW(
hTokDup,
NULL,
wszCmd,
NULL,
NULL,
FALSE,
dwCreationFlag,
pEnv,
NULL,
&stInfo,
&procInfo
);
if (FALSE == bRet)
{
if (NULL != pEnv)
{
DestroyEnvironmentBlock(pEnv);
}
CloseHandle(hTokDup);
return FALSE;
}
CloseHandle(procInfo.hProcess);
CloseHandle(procInfo.hThread);
if (NULL != pEnv)
{
DestroyEnvironmentBlock(pEnv);
}
CloseHandle(hTokDup);
return TRUE;
}

Credential Providers V2 Active for All users(Tiles)

I use sample code of "Credential Providers in Windows 10". I develop my code and change it very good.
But I have some problem with it:
It is not enable (Show tile) for all users in my windows. (Show for one user only)
I See this questions:
https://stackoverflow.com/a/31247811/3477587
Credential provider not displayed for all users (Other user included)
So I change my code but when use from my DLL win-login don't load and I must delete in in safe-mode to I can enter to my windows without Credential Providers.
I change my code as follow:
std::vector<CSamanCredential*> _pCredential; // SampleV2Credential
HRESULT CSamanProvider::GetCredentialAt(
DWORD dwIndex,
_Outptr_result_nullonfailure_ ICredentialProviderCredential** ppcpc)
{
HRESULT hr = E_INVALIDARG;
*ppcpc = nullptr;
hr = _pCredential[dwIndex]->QueryInterface(IID_PPV_ARGS(ppcpc));
return hr;
}
HRESULT CSamanProvider::GetCredentialCount(
_Out_ DWORD* pdwCount,
_Out_ DWORD* pdwDefault,
_Out_ BOOL* pbAutoLogonWithDefault)
{
*pdwDefault = CREDENTIAL_PROVIDER_NO_DEFAULT;
*pbAutoLogonWithDefault = FALSE;
if (_fRecreateEnumeratedCredentials)
{
_fRecreateEnumeratedCredentials = false;
_ReleaseEnumeratedCredentials();
_CreateEnumeratedCredentials();
}
DWORD dwUserCount = 0;
HRESULT hr;
if (_pCredProviderUserArray != nullptr) {
hr = _pCredProviderUserArray->GetCount(&dwUserCount);
}
if ((dwUserCount == 0) || (IsOS(OS_DOMAINMEMBER) == 1)) {
dwUserCount += 1;//display additional empty tile
}
*pdwCount = dwUserCount;
return S_OK;
}
void CSamanProvider::_ReleaseEnumeratedCredentials()
{
DWORD dwUserCount;
_pCredProviderUserArray->GetCount(&dwUserCount);
for (DWORD i = 0; i < dwUserCount; i++) {
if (_pCredential[i] != nullptr)
{
_pCredential[i]->Release();
_pCredential[i] = nullptr;
}
}
}
So I change other place in my code but I don't get result.
You must follow instructions in the posts you mentioned.
As a indirect response to ICredentialProviderSetUserArray::SetUserArray you must prepare tile for each user in the supplied list.
Later your tiles will be asked for ICredentialProviderCredential2::GetUserSid.
There your tile must return one of SIDs from the list of previous step.
When I was implementing this logic had to redesign a huge part of my code to support this feature.
I read this code. This is very helpful for knowing instruction and other details.
https://github.com/multiOTP/multiOTPCredentialProvider
This code (C++) active CP for all user on computer.
Thank you

Get all processes opened in a certain Desktop

I'm working on an application that creates a new desktop when launched and using a key combo I can move back and forth between the original and the new desktop. At creation time, in the new desktop a new explorer.exe process is started, so the user can start whatever applications he desires.
When the key combo that sends the exit command is detected, the new desktop is closed, and we return to the original one, but all the applications that the user started in the new desktop are still running.
Is there a way to get a handle on all of this processes opened in the new desktop, having a HANDLE for the Window Station and a HDESK handle for the new Desktop?
Thanks to David Heffernan's idea, I was able to find the following solution. Having a HDESK handle for the desktop, I compare it using GetThreadDesktop function with every thread from the system. I'm not sure that it's the most performant solution, I'm open towards suggestions for improvements, but this works just fine:
int main(void)
{
// Desktop handles
HDESK currentDesktop = GetsecondDesktop(GetCurrentThreadId());
HDESK secondDesktop = CreateDesktop(L"secondDesktop", NULL, NULL, 0, GENERIC_ALL, NULL);
// Start processes in secondDesktop ...
// Process enumeration
DWORD aProcesses[1024], cbNeeded, cProcesses;
unsigned int i;
EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded);
cProcesses = cbNeeded / sizeof(DWORD);
for (i = 0; i < cProcesses; i++)
{
if (aProcesses[i] != 0)
{
DWORD pThreadId = ListProcessThreads(aProcesses[i]);
if (GetsecondDesktop(pThreadId) == secondDesktop)
{
TerminateProcess(aProcesses[i]);
}
}
}
return 0;
}
DWORD ListProcessThreads(DWORD dwOwnerPID)
{
HANDLE hThreadSnap = INVALID_HANDLE_VALUE;
THREADENTRY32 te32;
// Take a snapshot of all running threads
hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (hThreadSnap == INVALID_HANDLE_VALUE)
return(FALSE);
// Fill in the size of the structure before using it.
te32.dwSize = sizeof(THREADENTRY32);
// Retrieve information about the first thread,
// and exit if unsuccessful
if (!Thread32First(hThreadSnap, &te32))
{
CloseHandle(hThreadSnap); // Must clean up the snapshot object!
return(FALSE);
}
// Now walk the thread list of the system,
// and display information about each thread
// associated with the specified process
do
{
if (te32.th32OwnerProcessID == dwOwnerPID)
{
return te32.th32ThreadID;
}
} while (Thread32Next(hThreadSnap, &te32));
// Don't forget to clean up the snapshot object.
CloseHandle(hThreadSnap);
return 0;
}
BOOL TerminateProcess(DWORD dwProcessId)
{
DWORD dwDesiredAccess = PROCESS_TERMINATE;
BOOL bInheritHandle = FALSE;
HANDLE hProcess = OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId);
if (hProcess == NULL)
return FALSE;
UINT uExitCode = 0;
BOOL result = TerminateProcess(hProcess, uExitCode);
CloseHandle(hProcess);
return result;
}

Denied access trying to open process

Description: I've gotten myself into a problem, I'm trying to open a process and read the memory of that process. It works all fine while debugging in my VS 2013 IDE however, if I build it and run the standalone executable as administrator (or lower credentials) the process cannot be opened properly, I am recieving error code 5, which is access denied.
The thing that confuses me is the fact it's working fine in the IDE but not with the standalone executable. I don't see why VS 2013 would have higher credentials than running a program as administrator.
A link to the code is here:
https://floobits.com/Simple2012/Simple_Bot
The important section is memoryReading.cpp line 30-35
A summary of the problem follows:
1. Everything works fine in visual Studio 2013.
2. The standalone executable is denied access when trying to open "the" process.
3. The executable is run as with full rights as administrator, so is the IDE.
I want to understand this a bit more detailed so I have two key questions, if anyone is in a good mood, I would love to have a very detailed explanation.
Question 1: How can I open the process with my standalone executable?
Question 2: Why does this problem occur the way it do?
If there's any information you're missing, don't hesitate to ask for it and I'll add it in as fast as possible. I also tried highlighing some parts to make it more comfortable to read and get a quick and brief idea of the problem.
I'm trying to open a process and read the memory of that process. It works all fine while debugging
This is because you user account has SE_DEBUG_NAME (SeDebugPrivilege). Its common for developers to develop with SE_DEBUG_NAME, but its not advised.
You should develop as a regular user account to ensure you don't get these kind of unexpected dependencies.
The thing that confuses me is the fact it's working fine in the IDE but not with the standalone executable...
Now that the issue cleared up...
Question 1: How can I open the process with my standalone executable?
Question 2: Why does this problem occur the way it do?
There are a few ways to fix it.
First, you can "compile" the privilege in by setting /MANIFESTUAC:level=requireAdministrator in the manifest options. "Compiling the privilege in" is a bit misleading because you will still be prompted by UAC. See /MANIFESTUAC on MSDN.
Second, you can set "Run as Administrator" on the program's properties. Right click the executable, then select the Compatibility tab. See Configure Applications to Always Run as an Administrator on Technet. You will be prompted by UAC.
Third, you can right click your executable, and then select "Run as Administrator". You will need to do this for each invocation of your program. You will be prompted by UAC.
Its not enough to "Run as Administrator". You will now need to enable a privilege or two. That's because Windows does not start your process with all privileges enabled (unlike Linux/Unix and su or sudo). Of the privileges listed at Privilege Constants, these are the three or four interesting ones:
SE_ASSIGNPRIMARYTOKEN_NAME
SE_DEBUG_NAME
SE_TCB_NAME
SE_INCREASE_QUOTA_NAME
Here's the code I use to enable privileges, like "SeDebugPrivilege":
BOOL CUserPrivilege::EnablePrivilege( LPCTSTR pszPrivilege, BOOL bEnabled ){
// Returned to caller
BOOL bResult = FALSE;
// Thread or Process token
HANDLE hToken = NULL;
__try {
bResult = OpenThreadToken( GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES, TRUE, &hToken );
if( !bResult )
{
bResult = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken );
assert( TRUE == bResult );
if( FALSE == bResult ) { __leave; }
}
bResult = EnablePrivilege( hToken, pszPrivilege, bEnabled );
DWORD dwError = GetLastError();
assert( TRUE == bResult || ( ERROR_SUCCESS == GetLastError() || ERROR_NOT_ALL_ASSIGNED == dwError ) );
// We're only enabling one privilege. If we get back
// ERROR_NOT_ALL_ASSIGNED, then we failed.
if( ERROR_NOT_ALL_ASSIGNED == dwError ) { bResult = FALSE; }
}
__finally {
if( NULL != hToken ) {
CloseHandle( hToken ); hToken = NULL;
}
}
return bResult;
}
BOOL CUserPrivilege::EnablePrivilege( HANDLE hToken, LPCTSTR pszPrivilege, BOOL bEnabled )
{
BOOL bResult = FALSE;
__try {
LUID luid;
TOKEN_PRIVILEGES priv;
bResult = LookupPrivilegeValue( NULL, pszPrivilege, &luid );
assert( TRUE == bResult );
if( FALSE == bResult ) { __leave; }
priv.PrivilegeCount = 1;
priv.Privileges[0].Luid = luid;
priv.Privileges[0].Attributes =
(bEnabled ? SE_PRIVILEGE_ENABLED : FALSE );
bResult = AdjustTokenPrivileges( hToken, FALSE, &priv, sizeof(priv), NULL, NULL );
// We're only enabling one privilege. If we get back
// ERROR_NOT_ALL_ASSIGNED, we failed.
if( ERROR_NOT_ALL_ASSIGNED == GetLastError() ) { bResult = FALSE; }
if( FALSE == bResult ) { __leave; }
bResult = TRUE;
}
__finally { ; }
return bResult;
}
You can check what privileges you have with code similar to below:
CUserPrivilege::Status CUserPrivilege::HasPrivilege( LPCTSTR pszPrivilege )
{
// Returned to caller
Status status = Error;
// Thread or Process token
HANDLE hToken = NULL;
// Scratch
BOOL bResult = FALSE;
__try {
bResult = OpenThreadToken( GetCurrentThread(), TOKEN_QUERY, TRUE, &hToken );
if( !bResult )
{
bResult = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken );
assert( TRUE == bResult );
if( FALSE == bResult ) { __leave; }
}
status = HasPrivilege( hToken, pszPrivilege );
}
__finally {
if( NULL != hToken ) {
CloseHandle( hToken ); hToken = NULL;
}
}
return status;
}
CUserPrivilege::Status CUserPrivilege::HasPrivilege( HANDLE hToken, LPCTSTR pszPrivilege )
{
// Returned to caller
Status status = Error;
// Scratch
BOOL bResult = FALSE;
PBYTE pBuffer = NULL;
TOKEN_PRIVILEGES* pTokenInfo = NULL;
__try
{
LUID uid = { 0, 0 };
bResult = LookupPrivilegeValue( NULL, pszPrivilege, &uid );
assert( TRUE == bResult );
if( FALSE == bResult ) { __leave; }
DWORD dwRequired = 0;
bResult = GetTokenInformation( hToken, TokenPrivileges, NULL, 0, &dwRequired );
assert( FALSE == bResult );
if( TRUE == bResult || 0 == dwRequired ) { __leave; }
pBuffer = new BYTE[dwRequired];
assert( NULL != pBuffer );
if( NULL == pBuffer ) { __leave; }
DWORD dwSize = dwRequired;
bResult = GetTokenInformation( hToken, TokenPrivileges, pBuffer, dwSize, &dwRequired );
assert( TRUE == bResult );
if( FALSE == bResult || dwSize != dwRequired ) { __leave; }
pTokenInfo = (TOKEN_PRIVILEGES*)pBuffer;
DWORD count = pTokenInfo->PrivilegeCount;
// Status changed...
status = Missing;
for( DWORD i = 0; i<count; i++ )
{
if( pTokenInfo->Privileges[i].Luid.HighPart == uid.HighPart &&
pTokenInfo->Privileges[i].Luid.LowPart == uid.LowPart )
{
DWORD attrib = pTokenInfo->Privileges[i].Attributes;
if( (attrib & SE_PRIVILEGE_ENABLED) ||
(attrib & SE_PRIVILEGE_ENABLED_BY_DEFAULT) )
{
status = Enabled;
}
else if( (attrib & SE_PRIVILEGE_REMOVED) )
{
status = Disabled;
}
break;
}
}
}
__finally
{
if( NULL != pBuffer ) {
delete[] pBuffer; pBuffer = NULL;
}
}
return status;
}
And here's the Status enumeration mentioned in the code:
enum Status { Missing = -1, Error = 0, Disabled = 1, Enabled = 2 };

C++ How to Check if an Outlook Process is already running

I am new to C++ programming but I would like to know if there is an easy way to check if an Outlook Process is already running, or in other words check if Outlook is already open.
Can anyone show me, please?
Thanks
You can check the running instance of the outlook OLE:
static const bool isOutlookRunning()
{
CLSID clsid;
HRESULT hr = CLSIDFromProgID( _T("Outlook.Application"), &clsid );
if( hr != S_OK ) return false;
IUnknown *pUnknown = NULL;
hr = GetActiveObject( clsid, 0, &pUnknown );
return ( hr == S_OK );
}
This code will not work if the app from you invoke it is running in different user security context than Outlook.
Its better to check for the process name.
//////////////////////////////////////////////////////////////////////
// IsProcessRunning
//////////////////////////////////////////////////////////////////////
bool IsProcessRunning(string &strProcessFullPathName)
{
// Get the list of process identifiers.
DWORD dwProcesses[2048];
DWORD dwSizeNeeded = 0;
DWORD dwProcessesCount = 0;
if ( !EnumProcesses( dwProcesses, sizeof(dwProcesses), &dwSizeNeeded ) )
{
_dwLastErrorCode = GetLastError();
_strLastError = "EnumProcesses";
return false;
}
dwProcessesCount = dwSizeNeeded / sizeof(DWORD);
string strToCheck = strProcessFullPathName;
transform(strToCheck.begin(), strToCheck.end(), strToCheck.begin(), tolower);
for(int i=0; i<(int)dwProcessesCount; i++ )
{
if( dwProcesses[i] != 0 )
{
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, dwProcesses[i]);
if(hProcess)
{
HMODULE hModule = NULL;
dwSizeNeeded = 0;
char cName[MAX_PATH];
if(EnumProcessModules(hProcess, &hModule, sizeof(DWORD), &dwSizeNeeded) )
{
if(GetModuleFileNameEx(hProcess, hModule, cName, MAX_PATH ) != 0)
{
string strName(cName);
// Convert to LowerCase
transform(strName.begin(), strName.end(), strName.begin(), tolower);
if(strName == strToCheck)
{
CloseHandle(hProcess);
return true;
}
}
}
CloseHandle(hProcess);
}
}
}
return false;
}
I assume that you are using Windows as platform, since Outlook normally runs under a Windows OS.
For a simple check you can use the Windows API functions EnumProcesses() and GetModuleBaseName() to determine the executable filename of the running processes and check if the executable name is "outlook.exe". A reference for the functions can be found in the MSDN.
Be aware that the this check may fail if the user runs another program that is using the same executable filename as Outlook. Another trap with the provided solution might be the access rights a user needs for the specified API calls.
Improvements might be to check the version information in the executable file too by using GetFileVersionInfo().
You can use CreateToolhelp32Snapshot and iterate through the running processes. If you need to heck for Outlook again (say you need to poll for the process), then save the process ID and use OpenProcess (many times faster). More details are given in the answer to this question:
Check whether one specific process is running on windows with C++