Add visible window titles to combobox MFC - c++

I want to add visible window titles to a combobox. Here is my source:
BOOL CALLBACK EnumWindowsProc(HWND hWnd, long lParam)
{
TCHAR buff[255];
CComboBox* pComboBox = (CComboBox*)GetDlgItem(IDC_COMBO_PROCESS);
if (IsWindowVisible(hWnd))
{
GetWindowText(hWnd, buff, 254);
pComboBox->AddString(buff);
}
return TRUE;
}
void CFindProcess::OnDropdownComboProcess()
{
EnumWindows(EnumWindowsProc, 0);
}
but I get error:
error C2660: 'GetDlgItem' : function does not take 1 arguments 60
How I can correctly add titles to combo?

MFC objects are thread-sensitive, GetDlgItem works well in the thread that created the object, probably the main UI thread. Function EnumWindows probably creates a worker thread to access the callback function, and that is why GetDlgItem failed to get a valid handle of the combobox.
To access the combobox properly in another thread, you have to use the static function: CWnd::FromHandle with the raw handle of the combobox object as follows:
BOOL CALLBACK EnumWindowsProc(HWND hWnd, long lParam)
{
if (IsWindowVisible(hWnd))
{ TCHAR szBuffer[255];
INT nLength = GetWindowText(hWnd, szBuffer, 254);
if (nLength>0)
{ // only add windows that has a caption
CComboBox *pComboBox = (CComboBox*)CWnd::FromHandle((HWND)lParam);
pComboBox->AddString(szBuffer);
}
}
return TRUE;
}
// call EnumWindows --------------------
CComboBox *pComboBox = (CComboBox *)GetDlgItem(IDC_COMBO1);
// passing the raw handle of the combobox as parameter
EnumWindows(EnumWindowsProc, (LPARAM)pComboBox->m_hWnd);

Firstly, your GetDlgItem has two parameters, and the first is a handle to the dialog box that contains the control.
So it expects a HWND parameter of the dialog that contains this control, I would presume that will be the HWND you pass as a parameter to your function.
CComboBox* pComboBox = (CComboBox*)GetDlgItem(hWnd,IDC_COMBO_PROCESS);
^^^^ added parameter
If you look at EnumWindows in MSDN, you'll see you have to pass a callback and it has a HWND parameter, if you look at what this parameter is for it says:
A handle to a top-level window.
This is exactly what you have to pass to GetDlgItem.
Also, you should check the return value of GetWindowText as this returns the number of characters written to the buff you passed it.
int ret = GetWindowText(hWnd, buff, 254);
if (ret > 0) pComboBox->AddString(buff); // only add non-empty strings.

In addition to what user #mfc has provided, I would not do UI update from a different thread. I believe EnumWindows does not create thread for enumeration. It would call the callbacks within the call-stack of current thread.
This, in turn, means that UI may freeze for a while. Thus, it is recommended to create a thread for enumeration. More over, I would not directly update UI from different thread. May be a vector of string, or a PostMessage (on each iteration) I would have used.
It is true that EnumWindows may perform quite fast. But when you move to enumerate other (kernel) objects like file, printers, users etc - the UI is definitely going to freeze. So, better practice writing multithreaded code. Initially writing MT-code would be a pain, but later you'd love it, appreciate it, and cannot live without it.

Related

Why constructor doesn't execute all the code using WinAPI?

This is my class constructor:
ActionButton::ActionButton(CallbackFunction function, void* param, HWND parent, int x, int y, int heigth, int width) :
m_function(function), m_parameters(param), m_window(NULL)
{
HWND m_window = CreateWindowEx(0, L"Action button", NULL, WS_CHILD | WS_VISIBLE,
x, y, width, heigth, parent, NULL, NULL, NULL);
DWORD dw = GetLastError();
SetWindowLongPtr(m_window, GWLP_USERDATA, (LONG_PTR)this);
ShowWindow(m_window, SW_NORMAL);
}
I used debuger and found that it executes CreateWindowEx() but after pressing F11 program jumped off the constructor (and I'm using only one thread). Is something wrong with my code?
After CreateWindowEx there is executing window procedure with parameters e.g WM_CREATE, so step after CreateWindowEx is not in constructor, after executing a few window procedure callbacks it goes back into constructor.
While executing CreateWindow[Ex] the system calls the window procedure associated with the window class for several messages (WM_GETMINMAXINFO, WM_NCCREATE, WM_NCCALCSIZE, WM_CREATE) before it returns. While the window procedure handles these messages the GWLP_USERDATA is not yet set. The system however guarantees, that GWLP_USERDATA is zero-initialized so you can safely query and handle the uninitialized GWLP_USERDATA.
If you want to set GWLP_USERDATA before CreateWindow[Ex] returns you will have to set up a CBT hook hook using SetWindowsHookEx and handle the HCBT_CREATEWND event. This lets you store any data attached to a HWND before the window procedure gets called with a WM_NCCREATE message.
Unrelated to your question, GWLP_USERDATA is fairly unreliable. A lot of applications will store their own data there, overwriting each other's data. Since this seems to be a private window class that you control you should allocate space in the Extra Window Memory instead and store your data there.

Application with multiple windows as instances of a class, C++

I wrote an application. There is a class named APP, with handle to the window, and message loop inside it, and all this stuff.
It is intended to "run" some objects of this class, each with its own window based on a set of variables necessary for a standard window.
Message loop is allowed for public use, it is ran by RunMessageLoop method.
int nCmdShow - of course, it is used to tell how to display a window.
Now, when i create some objects like this:
vector <APP *> App;
for (int i=0; i<3; i++)
{
App.push_back(&APP(nCmdShow))
App[i]->RunMessageLoop();
}
program waits for each message loop to end before it starts another.
I figured out to make it this way:
vector <APP *> App;
for (int i=0; i<3; i++)
{
App.push_back(&APP(nCmdShow))
}
for (int i=0; i<3; i++)
{
App[i]->RunMessageLoop();
}
When i know how many windows I want at startup to be run, it seems to be ok.
But I don't know how to create new windows dynamically, with complete independence of other windows. It should invoke message loops and immediately return to WinMain() without ending message loops.
I thought about multi-threaded app, each thread per one instance of an APP class. But don't know how to build multithreaded app, though.
Any ideas for a possible solution?
I see what you are trying to do now, I have achieved this in my application framework called Lucid (it is still a work in progress). For the sake of the answer, your window class will be called Window instead of APP.
This is done by passing a global procedure to every window you create. All windows share this same procedure. Every time any window gets a message, that message is sent to the global procedure, the global procedure checks if the HWND belongs to a Window that you created, and if it does, sends the message to that Windows' procedure. Here's an overview of how this works.
class Window
{
public:
// The contents of this function can vary from window to window
// provided that you make a subclass and override this method.
virtual LRESULT procedure(HWND wnd, UINT msg, WPARAM wp, LPARAM lp);
// When you create a Window object, add a pointer to it in this map.
// Eg. if (this->hwnd != NULL) createdWindows[this->hwnd] = this;
static map<HWND, Window*> createdWindows;
// When you create a window, make this its procedure.
static LRESULT CALLBACK routeMessage(HWND wnd, UINT msg, WPARAM wp, LPARAM lp)
{
if (createdWindows.find(wnd) != createdWindows.end()) {
// Message belongs to one of our 'Window' objects.
// Pass the message to that window and return the result.
return createdWindows[wnd]->procedure(wnd, msg, wp, lp);
} else {
// It seems you made 'routeMessage' the procedure
// of a window that doesn't belong in the map. Go ahead
// and process the message in the default manner.
return DefWindowProc(wnd, msg, wp, lp);
}
}
};
Now you will only need a single message loop and a single thread. I have a test project using Lucid that creates 2 windows with different procedures on a single thread with a single message loop:
#include "Lucid.h"
using namespace Lucid;
void sayBye(MessageEventArgs& e)
{
MessageBox(NULL, "Goodbye!", "Form 2", MB_OK);
e.handled = true;
}
void Program::onStart()
{
Form* myForm1 = new Form("Hello World!");
myForm1->show();
Form* myForm2 = new Form("Hello World!");
myForm2->addMessageHandler(WM_CLOSE, sayBye);
myForm2->show();
// This Program::onStart() function is called
// immediately before the single message loop is entered.
}
Create the threads with _beginthreadex equal to the number of window you need to run. Then, run message loop in the thread procedure and wait until all thread has been terminated with WaitForMultipleObjects.

Subclassing descendant of VCL TWinControl

Using pseudo funcs for subclassing:
CreateSpecialHandle(TWinControl *Control, const TCreateParams &Params, const AnsiString SubClass)
{
......;
set Control DefWndProc to SubClass.lpfnWndProc
set Control WindowHandle from CreateWindowEx
......;
subclass(TWinControl *Control);
}
subclass(TWinControl *Control)
{
......;
oldWProc = (void*)GetWindowLong(Control->Handle, GWL_WNDPROC);
oldDefWProc = (void*)(Control->DefWndProc);
oldWindowProc = Control->WindowProc;
MakeObjectInstance(newWProc) for SetWindowLong
MakeObjectInstance(newDefWProc) for Control->DefWndProc
Control->WindowProc = newWindowProc;
......;
}
Now, we have unexpected behavior of subclassed control.
WM_NCHITTEST result 0, etc...
For example when newWProc intercepts WM_NCHITTEST and sets Result to HTCLIENT
we have mouse response, but, is that not responding without setting msg.result to 1 for msg.msg WM_NCHITTEST consequence of my mistake and wrong subclassing, what else we need to handle manually?
newWProc make callback of oldWProc
newDefWProc make callback of oldDefWProc
newWindowProc calls oldWindowProc
Do we have to subclass parent control of subclassed control as well?
Also, sending WM_GETTEXT results with empty buffer.
Obviously, we are doing something wrong here. We need explanation,
Thank You all in advance
Update:
in TDCEdit:public TCustomEdit overriding CreateWindowHandle
void __fastcal CreateWindowHandle(const TCreateParams &Params)
{
CreateSpecialHandle(this,Params,TEXT("EDIT"));
}
void CreateSpecialHandle(TWinControl *Control,const TCreateParams &Params, AnsiString SubClass)
{
...
Control->WindowHandle = CreateWindowEx(...,"EDIT",....);
....
subclass(Control);
}
subclass(TWinControl* Control)
{
......;
oldWProc = (void*)GetWindowLong(Control->Handle, GWL_WNDPROC);
oldDefWProc = (void*)(Control->DefWndProc);
oldWindowProc = Control->WindowProc;
MakeObjectInstance(newWProc) for SetWindowLong
MakeObjectInstance(newDefWProc) for Control->DefWndProc
Control->WindowProc = newWindowProc;
......;
}
Now, when I use TDCEdit and intercept Message.Msg == WM_NCHITTEST
inside newWProc Message.Result is 0 and stay 0 through all message process chain.
Note that subclassing TCustomEdit is one among other controls we need to subclass
in project and we try to use same subclass(TWinControl*) function for all.
Here is part of newWProc with few more lines to focus on problem
void __fastcall TControlWrapper::newWProc(Messages::TMessage &Message)
{
if(Message.Msg == WM_NCHITTEST ) // TEST
if(Message.Result == 0)
Message.Result=1;//<- WHY I NEED TO DO THIS
if( Message.Msg == WM_DESTROY) {
HandleWMDestroy(Message);
return;
}
CallWindowProcW( (int(__stdcall*)())oldWProc,
Handle, Message.Msg, Message.WParam,
Message.LParam);
if(Message.Msg == WM_NCHITTEST )
if(Message.Result == 0)Message.Result=1;//<- OR THIS
}
This is a confusing question - it doesn't help that your code samples are not C++.
set Control DefWndProc to SubClass.lpfnWndProc
is not a line in a C++ function, for example. Can you show your actual code please?
I can make a guess at what you're trying to do: are you trying to subclass a window (perhaps a form?) so that it moves when the mouse is clicked on it? If so, you don't need to do any raw Windows API-style subclassing, the way you appear to be doing with GetWindowLong. In C++ Builder, the VCL is an object-oriented wrapper around the Windows API, and you can do this in one of two much cleaner ways:
Create a new WindowProc and set it; this is a property pointing to a new window procedure, and you simply call the old one too;
Create a descendant class of your TWinControl (if you're using a form, you already have one) and implement the virtual method WndProc.
An example of #1, in Delphi (but you should be easily able to convert it to C++) is in the Embarcadero documentation on subclassing WndProc.
An example of #2, the cleanest OO version, is here, and this actually shows how to do what you're trying to do, too: C++Builder: Create a TForm with BorderStyle bsNone that is nevertheless movable and resizable
Given what you appear to want to do, I would suggest going with #2.

C++ - WINAPI - Object-oriented approach to closing a window

While trying to create a nice wrapper around Win32 specific GUI components, I eventually ran into a problem. The problem is that I'm unable to close the application after the windows I created no longer exist.
My API works like this:
/// ----------------------------
/// #author God
/// #project Helixirr Widgets
/// ----------------------------
#include <helixirrwidgets/HelixirrWidgets.hpp>
int main(void){
HelixirrWidgets::Window __windows[2] = {HelixirrWidgets::Window("Big Window"), HelixirrWidgets::Window()};
__windows[0].position(200, 200);
__windows[0].size(800, 600);
__windows[0].visible(true);
__windows[0].save_changes();
__windows[1].name("Tiny Window");
__windows[1].position(10, 100);
__windows[1].size(400, 200);
__windows[1].visible(true);
__windows[1].save_changes();
while(__windows[0].active() || __windows[1].active()){
if(__windows[0].visible()){
__windows[0].show();
}
if(__windows[1].visible()){
__windows[1].show();
}
}
return 0;
}
In method of HelixirrWidgets::Window called "active", which is declared like this
inline bool active(void) const noexcept;
I can check, whether my window is active or not.
This method basically return a const reference to a boolean member variable of an instance. This member variable is modified in "show"-method of the same class. Here's the definition:
void Window::show(void){
if(GetMessage(&_m_opHelper->message, _m_opHelper->handle_window, 0, 0)){
if(_m_opHelper->message.message == WM_CLOSE){
_m_bActive = false;
return;
}
TranslateMessage(&_m_opHelper->message);
DispatchMessage(&_m_opHelper->message);
ShowWindow(_m_opHelper->handle_window, SW_SHOWDEFAULT);
UpdateWindow(_m_opHelper->handle_window);
_m_bActive = true;
return;
}
_m_bActive = false;
}
Do note I use pimpl-idiom to hide platform-specific structures ("_m_opHelper" is pointer to implementation).
It may look like it works, but it doesn't and I can't understand why. It all comes down to a simple question: how can I close my window implemented using WINAPI specific functions and structures to be closed appropriately by a user of my application?
I guess the cause of the issue is related to the fact WM_CLOSE simply is not last message HWND gets. Messages like WM_DESTROY, WM_NCDESTROY and possibly more (depending on the particlar window and its state) will come after WM_CLOSE, leading to the assignment _m_bActive = TRUE.
I.e. the window becomes inactive for very short time, and (likely) they will never be inactive at the same time, causing an endless loop in main().

Notify CDialog-Window when selecting another window

I got a dialog-based MFC-Tool that is supposed to show the title of a window of another application in a messagebox when i click on it.
My Problem is that the WM_KILLFOCUS doesn't work here. Maybe I'm doing it wrong.
I do the following:
BEGIN_MESSAGE_MAP(CMyDlg, CDialog)
ON_WM_KILLFOCUS()
END_MESSAGE_MAP()
...
...
void CMyDlg::OnKillFocus( CWnd* pNewWnd )
{
CDialog::OnKillFocus(pNewWnd);
if(m_bSelectorModeActive)
{
HWND hwnd(GetForegroundWindow());
TCHAR buf[512];
::GetWindowText(hwnd, buf, 512);
MessageBox(buf);
}
}
Any idea what's wrong?
This is my guess
Replace HWND hwnd(GetForegroundWindow()); with GetActiveWindow(void) .
I solved it, thanks for your efforts.
Yes, i do use CStrings, this was just a little example of a bit more complex thing i do. My problem was not the function itself but the event WM_KILLFOCUS that didn't seem to work.
Maybe I was not clear enough here, sorry.
WM_ACTIVATE does what i need. It notifies my dialog when the focus is set and/or lost.
The code you've shown shouldn't even compile. The GetForegroundWindow function provided by MFC doesn't return an HWND, so you can't initialize the hwnd variable using its return value.
If you want to get an HWND, you need to call GetForegroundWindow from the Windows API by escaping the call with ::, just like you did for GetWindowText. So simply rewrite your code as follows:
void CMyDlg::OnKillFocus( CWnd* pNewWnd )
{
CDialog::OnKillFocus(pNewWnd);
if(m_bSelectorModeActive)
{
HWND hwnd(::GetForegroundWindow());
TCHAR buf[512];
::GetWindowText(hwnd, buf, 512);
MessageBox(buf);
}
}
Beyond that, in looking at your code, one wonders that you seem to be ignoring the object-orientation MFC so humbly attempts to bring to the Windows API. You shouldn't need to work directly with window handles. And one could argue that the most compelling reason to use MFC is its CString class. There's no reason you should have to deal with an array of TCHARs anymore. I might write this instead:
void CMyDlg::OnKillFocus( CWnd* pNewWnd )
{
CDialog::OnKillFocus(pNewWnd);
if(m_bSelectorModeActive)
{
CWnd* pForeWnd = GetForegroundWindow();
CString windowText;
pForeWnd->GetWindowText(windowText);
MessageBox(windowText);
}
}