20using namespace KontactInterface;
32#include "kontactinterface_debug.h"
33#include <QCoreApplication>
36PSID copySid(PSID from)
42 int sidLength = GetLengthSid(from);
43 PSID to = (PSID)malloc(sidLength);
44 CopySid(sidLength, to, from);
49static PSID getProcessOwner(HANDLE hProcess)
54 OpenProcessToken(hProcess, TOKEN_READ, &hToken);
57 PTOKEN_USER userStruct;
60 GetTokenInformation(hToken, TokenUser, NULL, 0, &size);
61 if (ERROR_INSUFFICIENT_BUFFER == GetLastError()) {
62 userStruct =
reinterpret_cast<PTOKEN_USER
>(
new BYTE[size]);
63 GetTokenInformation(hToken, TokenUser, userStruct, size, &size);
65 sid = copySid(userStruct->User.Sid);
75static HANDLE getProcessHandle(
int processID)
77 return OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | PROCESS_TERMINATE,
false, processID);
80void KontactInterface::getProcessesIdForName(
const QString &processName,
QList<int> &pids)
85 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
86 if (h == INVALID_HANDLE_VALUE) {
90 pe32.dwSize =
sizeof(PROCESSENTRY32);
91 if (!Process32First(h, &pe32)) {
99 PSID user_sid = getProcessOwner(GetCurrentProcess());
102 HANDLE hProcess = getProcessHandle(pe32.th32ProcessID);
107 PSID sid = getProcessOwner(hProcess);
108 PSID userSid = getProcessOwner(GetCurrentProcess());
109 if (!sid || userSid && !EqualSid(userSid, sid)) {
114 pids.
append((
int)pe32.th32ProcessID);
115 qCDebug(KONTACTINTERFACE_LOG) <<
"found PID: " << (int)pe32.th32ProcessID;
117 }
while (Process32Next(h, &pe32));
121struct EnumWindowsStruct {
130BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
132 if (GetWindowLong(hwnd, GWL_STYLE) & WS_VISIBLE) {
135 GetWindowThreadProcessId(hwnd, &pidwin);
136 if (pidwin == ((EnumWindowsStruct *)lParam)->pid) {
137 ((EnumWindowsStruct *)lParam)->windowId = hwnd;
144void KontactInterface::activateWindowForProcess(
const QString &executableName)
147 KontactInterface::getProcessesIdForName(executableName, pids);
150 for (
int pid : std::as_const(pids)) {
152 qCDebug(KONTACTINTERFACE_LOG) <<
"activateWindowForProcess(): PID to activate:" << pid;
160 EnumWindowsStruct winStruct;
161 winStruct.pid = foundPid;
162 EnumWindows(EnumWindowsProc, (LPARAM)&winStruct);
163 if (winStruct.windowId == 0) {
166 SetForegroundWindow(winStruct.windowId);
This file is part of the kpimutils library.
void append(QList< T > &&value)
QString fromWCharArray(const wchar_t *string, qsizetype size)