Window APIs are new for me. I am trying to find the number of windows that are open from windows desktop application. I wanted to open only one instance of an application.
I have my application abc.exe. If user tries to open the abc.exe application for the first time then the abc.exe application will open normally. But, if abc.exe application is already open and the usser tries to open it again then it should give an already open instance of Application.
I am able to get an already open instance with help from the below code in specific condition.
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam) {
HWND *retHwnd = (HWND *)lParam;
if (*retHwnd) {
return FALSE;
}
DWORD procID = 0;
auto threadID = GetWindowThreadProcessId(hwnd, &procID);
auto handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, procID);
QString fileName;
if (handle) {
TCHAR filename[FILENAME_MAX];
auto len = GetModuleFileNameEx(handle, NULL, filename, FILENAME_MAX);
fileName = QFileInfo(QString::fromWCharArray(filename, len)).fileName();
if (GetLastApplicationName() == fileName) {
*retHwnd = hwnd;
}
CloseHandle(handle);
}
return TRUE;
}
void ShowExistingInstance() {
HWND hwnd = 0;
auto res = EnumWindows(&EnumWindowsProc, (LPARAM)&hwnd);
if (hwnd) {
ShowWindow(hwnd, SW_MINIMIZE);
ShowWindow(hwnd, SW_MINIMIZE);
ShowWindow(hwnd, SW_RESTORE);
}
}
However, I am not getting first instance of the application if two windows are open from the application.
Below I mention two situations. In the first situation the code works fine, and in the second situation the code the code does not work fine.
1) Get already open instance of application
Steps:
a. User clicks on abc.exe application icon.
b. Main window is open for example its name is mainWindow1.
c. Restore-down or Minimize mainWindow1
d. User clicks abc.exe again using the application icon
e. Here I am getting mainWindow1, and it is correct.
2) Does not get already open instance of application
Steps:
a. User clicks on abc.exe application icon.
b. Main window is open for example its name is mainWindow1.
c. User opens another window from the current application for example its name is mainWindow2. (mainWindow1 is not parent of mainWindow2).
d. Restore-down or Minimize mainWindow1
(here mainWindow2 is also minimized or Restore- down automatically w.r.t mainWindow1)
e. User clicks abc.exe again using the application icon.
f. Here I am getting mainWindow2 instead of mainWindow1.
I wanted some kind of guide line for windows API, which is help me to find the Hwnd of Mainwidnow1 in second situation.
I got my functionality with help of below code
BOOL isMainWindow(HWND handle) {
return GetWindow(handle, GW_OWNER) == (HWND)0 && IsWindowVisible(handle);
}
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam) {
HWND *retHwnd = (HWND *)lParam;
if (*retHwnd) {
return FALSE;
}
DWORD procID = 0;
auto threadID = GetWindowThreadProcessId(hwnd, &procID);
if (!isMainWindow(hwnd)) {
return TRUE;
}
auto handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, procID);
QString fileName;
if (handle) {
TCHAR filename[FILENAME_MAX];
auto len = GetModuleFileNameEx(handle, NULL, filename, FILENAME_MAX);
fileName = QFileInfo(QString::fromWCharArray(filename, len)).fileName();
if (GetLastApplicationName() == fileName) {
*retHwnd = hwnd;
}
CloseHandle(handle);
}
return TRUE;
}
void ShowExistingInstance() {
HWND hwnd = 0;
auto res = EnumWindows(&EnumWindowsProc, (LPARAM)&hwnd);
if (hwnd) {
ShowWindow(hwnd, SW_MINIMIZE);
ShowWindow(hwnd, SW_MINIMIZE);
ShowWindow(hwnd, SW_RESTORE);
}
}
Related
How can I have a Windows tray notification icon for an out-of-process COM server, developed using VS2019?
So far I have tried just adding one with Shell_NotifyIconA(NIM_ADD, &n); as per the MSDN documentation. .However if I set the NOTIFYICONDATA::m_hWnd to 0 then this call is rejected with 0x80004005 (Invalid handle).
So I have to specify a window handle that the icon's messages will go to, but the application currently doesn't have any windows. It does have a message pump which is found at ATL::CAtlExeModule<T>::RunMessageLoop() (that's part of the ATL boilerplate code) but I can't see any mention of where a window handle is to send messages to this loop.
I've tried using a Message-only Window created with CWindowImpl::Create, however when the program runs, the behaviour is unexpected. A blank space appears in the notification tray (the icon does not show properly), and mousing or clicking on the space does not cause the message handler to be entered. The log message appears indicating Shell_NotifyIcon() succeeded and the handles are valid, but no further log messages.
What's the right way to do this in VS2019? (I have done it before in C++Builder which lets you simply add a form, mark it as the main form, and add a notification icon component to it).
Code for the ATLExeModule (this is the boilerplate code plus my modifications):
class CNotifyWnd : public CWindowImpl<CNotifyWnd>
{
public:
BEGIN_MSG_MAP(CMyCustomWnd)
MESSAGE_HANDLER(WM_USER+1, OnMsg)
END_MSG_MAP()
LRESULT OnMsg(UINT, WPARAM, LPARAM, BOOL&)
{
DEBUG_LOG("Received notification");
return 0;
}
};
static void create_notifyicon()
{
auto * pw = new CNotifyWnd;
HWND hwnd = pw->Create(HWND_MESSAGE);
auto hInst = GetModuleHandle(NULL);
NOTIFYICONDATAA n{};
n.cbSize = sizeof n;
n.hIcon = LoadIcon(NULL, IDI_SHIELD);
#pragma warning(disable : 4996)
strcpy(n.szTip, "Tooltip string");
n.dwInfoFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE;
n.uVersion = NOTIFYICON_VERSION;
n.hWnd = hwnd;
n.uID = 1234;
n.uCallbackMessage = WM_USER + 1;
int hr = Shell_NotifyIconA(NIM_ADD, &n);
DEBUG_LOG("Shell_NotifyIcon = {}; Icon handle {}, window {}",
hr, (uint64_t)n.hIcon, (uint64_t)n.hWnd);
}
class CMyProjectModule : public ATL::CAtlExeModuleT< CMyProjectModule >
{
public :
DECLARE_LIBID(LIBID_MyProjectLib)
DECLARE_REGISTRY_APPID_RESOURCEID(IDR_MYPROJECT, "{d0d2e9f7-8578-412a-9311-77ff62291751}")
using Parent = ATL::CAtlExeModuleT< CMyProjectModule >;
HRESULT PreMessageLoop(int nShowCmd) throw()
{
HRESULT hr = Parent::PreMessageLoop(nShowCmd);
create_notifyicon();
return hr;
}
};
CMyProjectModule _AtlModule;
extern "C" int WINAPI _tWinMain(HINSTANCE /*hInstance*/, HINSTANCE /*hPrevInstance*/,
LPTSTR /*lpCmdLine*/, int nShowCmd)
{
return _AtlModule.WinMain(nShowCmd);
}
The code in the question is mostly correct, however dwInfoFlags should be uFlags. After making that change the notify icon worked as intended.
Thanks to commentors who suggested ways to simplify the original code in the question, and the idea of a "message-only window" created by setting the parent to HWND_MESSAGE.
I want to write a program that needs sometimes to start processes of another applications (mainly Sumatra PDF) on Windows 10, version 1803 (April 2018 Update).
These applications should be started on a specific monitor. I also want to be able to close the processes when needed.
The preferred languages are C# and Java, but any help is appreciated.
EDIT
I've tried to use the ShellExecuteExW function suggested by IInspectable in C++ code directly, but it doesn't work, as applications appear on the main monitor. I must have certainly made a mistake as I am absolutely new to WinAPI and know very little C++.
#include <Windows.h>
HMONITOR monitors[2]; // As it's only a test and I have currently only two monitors.
int monitorsCount = 0;
BOOL CALLBACK Monitorenumproc(HMONITOR hMonitor, HDC hdc, LPRECT lprect, LPARAM lparam)
{
monitors[monitorsCount] = hMonitor;
monitorsCount++;
return TRUE;
}
int main()
{
EnumDisplayMonitors(NULL, NULL, Monitorenumproc, 0);
_SHELLEXECUTEINFOW info;
ZeroMemory(&info, sizeof(info));
info.cbSize = sizeof(info);
info.fMask = SEE_MASK_HMONITOR;
//info.lpVerb = L"open";
info.lpFile = L"C:\\Windows\\System32\\cmd.exe";
info.nShow = SW_SHOW;
info.hMonitor = monitors[1]; // Trying to start on the second monitor.
ShellExecuteExW(&info);
return 0;
}
As suggested by others, this is intended behavior of Windows and for the good reasons.
Also, you can not rely on default window placement atleast for SumatraPDF, since it surely does not use CW_USEDEFAULT, and instead stores these values in :
%USERPROFILE%\AppData\Roaming\SumatraPDF\SumatraPDF-settings.txt
There are multiple options though:
Use third party tools that monitor top level windows and based on pre-configured rules moves them to specified display. E.g. DisplayFusion, etc.
Use ligher weight solutions like AutoHotkey/AutoIt.
Try and do this in code itself. Following is a working solution. I smoke tested on my box.
Disclaimer: I have not written the entire code, for saving time I pulled it up from couple of sources, tweaked it, glued it together, and tested with SumantraPDF. Do also note, that this code is not of highest standards, but solves your problem, and will act as a can-be-done example.
C++ code: (scroll down for C# code)
#include <Windows.h>
#include <vector>
// 0 based index for preferred monitor
static const int PREFERRED_MONITOR = 1;
struct ProcessWindowsInfo
{
DWORD ProcessID;
std::vector<HWND> Windows;
ProcessWindowsInfo(DWORD const AProcessID)
: ProcessID(AProcessID)
{
}
};
struct MonitorInfo
{
HMONITOR hMonitor;
RECT rect;
};
BOOL WINAPI EnumProcessWindowsProc(HWND hwnd, LPARAM lParam)
{
ProcessWindowsInfo *info = reinterpret_cast<ProcessWindowsInfo*>(lParam);
DWORD WindowProcessID;
GetWindowThreadProcessId(hwnd, &WindowProcessID);
if (WindowProcessID == info->ProcessID)
{
if (GetWindow(hwnd, GW_OWNER) == (HWND)0 && IsWindowVisible(hwnd))
{
info->Windows.push_back(hwnd);
}
}
return true;
}
BOOL CALLBACK Monitorenumproc(HMONITOR hMonitor, HDC hdc, LPRECT lprect, LPARAM lParam)
{
std::vector<MonitorInfo> *info = reinterpret_cast<std::vector<MonitorInfo>*>(lParam);
MonitorInfo monitorInfo = { 0 };
monitorInfo.hMonitor = hMonitor;
monitorInfo.rect = *lprect;
info->push_back(monitorInfo);
return TRUE;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
// NOTE: for now this code works only when the window is not already visible
// could be easily modified to terminate existing process as required
SHELLEXECUTEINFO info = { 0 };
info.cbSize = sizeof(info);
info.fMask = SEE_MASK_NOCLOSEPROCESS;
info.lpFile = L"C:\\Program Files\\SumatraPDF\\SumatraPDF.exe";
info.nShow = SW_SHOW;
std::vector<MonitorInfo> connectedMonitors;
// Get all available displays
EnumDisplayMonitors(NULL, NULL, Monitorenumproc, reinterpret_cast<LPARAM>(&connectedMonitors));
if (ShellExecuteEx(&info))
{
WaitForInputIdle(info.hProcess, INFINITE);
ProcessWindowsInfo Info(GetProcessId(info.hProcess));
// Go though all windows from that process
EnumWindows((WNDENUMPROC)EnumProcessWindowsProc, reinterpret_cast<LPARAM>(&Info.ProcessID));
if (Info.Windows.size() == 1)
{
// only if we got at most 1 window
// NOTE: applications can have more than 1 top level window. But at least for SumtraPDF this works!
if (connectedMonitors.size() >= PREFERRED_MONITOR)
{
// only move the window if we were able to successfully detect available monitors
SetWindowPos(Info.Windows.at(0), 0, connectedMonitors.at(PREFERRED_MONITOR).rect.left, connectedMonitors.at(PREFERRED_MONITOR).rect.top, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
}
}
CloseHandle(info.hProcess);
}
return 0;
}
To emphasize one of my comments in code. This code will only work if the process in question is not already running. You can tweak the code as per your requirements otherwise.
Update: Added C# code below, as I realized OP prefers C#. This code also has the termination logic cooked in.
C# code:
[DllImport("user32.dll", SetLastError = true)]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);
private const int SWP_NOSIZE = 0x0001;
private const int SWP_NOZORDER = 0x0004;
private const int PREFERRED_MONITOR = 1;
static void Main(string[] args)
{
// NOTE: you will have to reference System.Windows.Forms and System.Drawing (or
// equivalent WPF assemblies) for Screen and Rectangle
// Terminate existing SumatraPDF process, else we will not get the MainWindowHandle by following method.
List<Process> existingProcesses = Process.GetProcessesByName("SumatraPDF").ToList();
foreach (var existingProcess in existingProcesses)
{
// Ouch! Ruthlessly kill the existing SumatraPDF instances
existingProcess.Kill();
}
// Start the new instance of SumantraPDF
Process process = Process.Start(#"C:\Program Files\SumatraPDF\SumatraPDF.exe");
// wait max 5 seconds for process to be active
process.WaitForInputIdle(5000);
if (Screen.AllScreens.Length >= PREFERRED_MONITOR)
{
SetWindowPos(process.MainWindowHandle,
IntPtr.Zero,
Screen.AllScreens[PREFERRED_MONITOR].WorkingArea.Left,
Screen.AllScreens[PREFERRED_MONITOR].WorkingArea.Top,
0, 0, SWP_NOSIZE | SWP_NOZORDER);
}
}
SEE_MASK_HMONITOR is only a request. Applications can choose their own window placement. SEE_MASK_HMONITOR only works when the executed application relies on default window placement, i.e. it creates its first top-level window with CW_USEĀDEFAULT
So what you want is not generally possible. Your code is as good as you can get, if you don't control the launched application.
I'm trying to create an application that will be notified about each active window change in Windows so it could do some tasks like detecting window titles, therefore "punishing" bad people accessing bad content on our PC machines. So, this is really important for the application because it's purpose is to log "bad" applications from history.
So, in my main function, I started a thread for my WindowLogger.
windowThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) WindowLogger,
(LPVOID) argv[0], 0, NULL );
if (windowThread)
{
// Also a bit of protection here..
return WaitForSingleObject(windowThread, INFINITE);
}
Then, here is my WindowLogger procedure:
// Function called by main function to install hook
DWORD WINAPI
WindowLogger(LPVOID lpParameter)
{
HHOOK hWinHook;
HINSTANCE hExe = GetModuleHandle(NULL);
if (!hExe)
{
return 1;
}
else
{
hWinHook = SetWindowsHookEx(WH_CBT, (HOOKPROC) CBTProc, hExe, 0);
MSG msg;
// I AM UNSURE ABOUT THIS PART..
// Probably wrong code :D ..
while (GetMessage(&msg, NULL, 0, 0) != 0)
{
if (msg.message == HCBT_ACTIVATE) {
// my code to log the window name
}
}
UnhookWindowsHookEx(hWinHook);
}
return 0;
}
And finally, my CBTProc callback function, it logs the windows using my log() function:
LRESULT CALLBACK
CBTProc(int nCode, WPARAM wParam, LPARAM lParam)
{
switch (nCode)
{
case HCBT_ACTIVATE:
{
HWND foreground = GetForegroundWindow();
char window_title[50];
if (foreground)
GetWindowText(foreground, window_title, 25);
log("|");
log(&window_title[0]);
log("|");
}
}
}
So I had debugged the program and what I figured out is that hWinHook becomes NULL after SetWindowsHookEx() -- this is what probably causes my program to mailfunction..
.. Can you help me out with this?
Thanks in advance.
Passing 0 for the dwThreadId parameter to SetWindowsHookEx is used to register a hook for all threads in the system, i.e. a global hook. However to do this, your hook code needs to be located within a DLL (so that the DLL can be mapped into the address space of other processes). Since your hook code is in your main executable rather than a DLL the call is failing.
I would like to write a program, which lets me change a values in text box of different program, or automatically copy a values from one program to another.
I found a way to get hWnd to most (no idea if all of them) of controls in targer program, and to point them with mouse cursor. I made a simple struct to do so, and an array of it
struct hWndpointer
{
HWND hWnd;
AnsiString text;
};
hWndpointer tbl[250];
The EnumWindowProc and EnumChildWindowProc loads handles and text of the window into the array and into the list control in my program, so i can click an item on the list (or select it with keyboard) and the cursor points the control (like button or textbox) like expected... Unfortunately there are some controls with no text (or rather GetWindowText returns no text) so there is no way to identify the control.
The question is:
Is there any way to get/read a NAME of the control?
Is there any way to get/read and set a specyfic value like 'enabled' or 'text' or 'value'?
Thanks in advance
PS: Sorry for my english ;)
You can use SendMessage and PostMessage to send WM_GETTEXT, WM_SETTEXT, WM_ENABLE to windows owned by other processes. (SendMessage for queries, PostMessage for write-only actions)
Often the child ID will be used to identify subwindows (especially in a dialog), but it's also possible for a program to rely purely on the dynamic HWND values, in which case you'll have to fall back to window positions to differentiate.
From the Win32 API's perspective, UI controls do not have Names, so you cannot ask the API to return the Name of a UI control in another process because such a value does not exist. Names are strictly a feature of the UI framework being used by the app (VCL in the case of C++Builder), and you cannot directly access frameworks across process boundaries. You would need cooperation from the control's owning app.
For instance, one way would be to have both apps call RegisterWindowMessage() to register a custom window message, then your app can post that message to the other app specifying the desired control's HWND and your own HWND as parameters. The other app can then SendMessage() the control's Name back to your app's HWND using the WM_COPYDATA message, which you can use to update your list accordingly.
In the VCL framework, you can convert an HWND to a TWinControl* pointer using the FindControl() function. It will return NULL if the HWND does not belong to the calling process, otherwise you can then copy the value from its Name property. For example:
const UINT WM_GETCONTROLNAME = RegisterWindowMessage("WM_GetControlName");
const UINT WM_GETCONTROLNAME_RESULT = RegisterWindowMessage("WM_GetControlName_Result");
#include <pshpack1.h>
struct sControlName
{
HWND hWnd;
int Length;
char Value[1];
};
#include <poppack.h>
void __fastcall TMyForm::WndProc(TMessage &Message)
{
if ((Message.Msg == WM_COPYDATA) && (WM_GETCONTROLNAME_RESULT != 0))
{
LPCOPYDATASTRUCT cds = (LPCOPYDATASTRUCT) Message.LParam;
if (cds->dwData == WM_GETCONTROLNAME_RESULT)
{
sControlName *pName = (sControlName*) cds->lpData;
AnsiString sName(pName->Value, pName->Length);
// locate pName->hWnd in your list and assign sName to it as needed...
return;
}
}
TForm::WndProc(Message);
}
void ___fastcall TMyForm::FillList()
{
...
if (WM_GETCONTROLNAME != 0)
{
HWND TheControlHWND = ...;
HWND OtherAppHWND = ...;
PostMessage(OtherAppHWND, WM_GETCONTROLNAME, (WPARAM)TheControlHWND, (LPARAM)this->Handle);
}
...
}
.
const UINT WM_GETCONTROLNAME = RegisterWindowMessage("WM_GetControlName");
const UINT WM_GETCONTROLNAME_RESULT = RegisterWindowMessage("WM_GetControlName_Result");
#include <pshpack1.h>
struct sControlName
{
HWND hWnd;
int Length;
char Value[1];
};
#include <poppack.h>
void __fastcall TMyForm::WndProc(TMessage &Message)
{
if ((Message.Msg == WM_GETCONTROLNAME) && (WM_GETCONTROLNAME != 0) && (WM_GETCONTROLNAME_RESULT != 0))
{
HWND hWnd = (HWND) Message.WParam;
TWinControl *Ctrl = FindControl(hWnd);
if (Ctrl)
{
AnsiString sName = Ctrl->Name;
std::vector<unsigned char> buffer((sizeof(sControlName) - 1) + sName.Length());
sControlName *pName = (sControlName*) &buffer[0];
pName->hWnd = hWnd;
pName->Length = sName.Length();
strncpy(pName->Value, sName.c_str(), pName->Length);
COPYDATASTRUCT cds = {0};
cds.dwData = WM_GETCONTROLNAME_RESULT;
cds.cdData = buffer.size();
cds.lpData = pName;
SendMessage((HWND)Message.LParam, WM_COPYDATA, (WPARAM)this->Handle, (LPARAM)&cds);
}
return;
}
TForm::WndProc(Message);
}
I have been trying various code snippets here and there, but still not successful.I am simply trying to find one of the open windows (it is the Browser window) using FindWindow(NULL,WINDOWTITLE), with a specific Title string. Once I get the handle of the window, I need the coordinates using GetWindowRect.
This code gets me the coordinates, but seems like it's in an infinite loop, there are about a 100 lines of output with the coordindates, should be just 1. I don't see any while construct (originally a Java programmer)... wonder why it's repeating...
struct WindowInfo
{
HWND m_hWnd;
string m_title;
WindowInfo(HWND hwnd, string title) : m_hWnd(hwnd), m_title(title) {}
};
BOOL CALLBACK EnumWindowsProc(HWND hwnd,LPARAM lParam)
{
vector<WindowInfo*> & windows = *(vector<WindowInfo*>*)lParam;
char title[256];
HANDLE wndHandle;
LPCWSTR WINDOWTITLE = L"eBargain 2 Share - Windpos Internet Explorer";
RECT rRect;
LPRECT lpRect;
RECT rc;
hwnd = FindWindow(NULL,WINDOWTITLE);
GetWindowRect(hwnd,&rc);
printf("Position: %d x %d\tSize: %d x %d\n",rc.left,rc.top,rc.right- rc.left,rc.bottom-rc.top);
/* Enumerating through all the windows tells me that I am on the right track... (Should I just try to find the TITLE STRING by comparing every title from the following enumeration ?
*/
GetWindowTextA(hwnd, title, 256);
windows.push_back(new WindowInfo(hwnd,title));
// printf("%s\n", title);
return TRUE;
}
int main()
{
vector<WindowInfo*> windows;
BOOL ret = EnumWindows(EnumWindowsProc, (LPARAM) &windows);
if ( ret )
{
//windows have windowinfo of all enumerated windows
}
}
Your EnumWindowsProc seems to be a bit confused - are you enumerating or using FindWindow?
If you enumerate, simply get the window title and compare to the string you search for:
BOOL CALLBACK EnumWindowsProc(HWND hwnd,LPARAM lParam)
{
char title[256];
if (GetWindowTextA(hwnd, title, 256)) {
if (strcmp(title, "eBargain 2 Share - Windpos Internet Explorer") == 0) {
/* GetWindowRect ... */
}
}
return TRUE;
}
Or, if you're using FindWindow, no need to enumerate:
int main() {
HWND hwnd = FindWindowA(0, "eBargain 2 Share - Windpos Internet Explorer");
if (hwnd) {
/* GetWindowRect ... */
}
}