C++ Builder 2009 - How to Determine if Control's Window is Visible - c++

I have a TWinControl and am trying to determine if the parent window is visible.
I see TWinControl has a property of ParentWindow. The return type of ParentWindow is void *. So I'm curious if I must cast to a particular type, which would then give me access to check if the window is visible or not.
Does anyone know the type I need to cast to, or another way to accomplish this?
Additional Troubleshooting Notes, Part 1:
I tried to get the ParentWindows class by:
String parentWindowClassName = ((TObject *)(Control->ParentWindow))->ClassName();
But this gave an access violation. I also tried casting to TForm, which also gave an access violation, which makes me believe the parent window may be controlled by windows. If so, does anyone know of any trick to check if it is visible? E.g. Any COM tricks or anything?
Additional Troubleshooting Notes, Part 2:
The answer to this question may help solve my other question: C++ Builder 2009 - Cannot focus a disabled or invisible window
However the other question may be solved without this approach, which is why I posted a different question.
Additional Troubleshooting Notes, Part 3:
Thanks for the extra info Ken. I got my info off code assist:
However I see your HWND return type from: http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/delphivclwin32/Controls_TWinControl_ParentWindow.html
That might be the extra info I need... will post a solution if I get it working. Thx.

#KenWhite, your suggestions gave me what I needed, thanks!
The following is the code that solved my problem:
#include "winuser.h"
...
void SafeSetFocus(TWinControl *Control)
{
HWND hWnd = Control->ParentWindow;
bool parentIsVisible = IsWindowVisible(hWnd);
if(Control->Enabled && Control->Visible && parentIsVisible)
{
Control->SetFocus();
}
}

Related

XLib - Window hints behave differently when I construct XWindowAttributes in the main function?

I am experimenting with some fundamental Xlib stuff. I am creating a basic window and creating an OpenGL context for it.
I am trying to prevent the user from being able to resize or manually full screen the window. I added the code:
XSizeHints hints;
hints.min_width = hints.max_width = setup.w;
hints.min_height = hints.max_height = setup.h;
XSetWMNormalHints(dpy, win, &hints);
This worked at first. However after experimenting with it I have found that it mysteriously stops working sometimes. It is not a matter of unusual window managers or anything like that, I am using the default windows manager installed with Ubuntu. What causes it to change, strangly enough, is whether or not I include this line in main:
XWindowAttributes atts;
It does not matter where I put it. At the beginning, or inside a loop, or even after the return. As long as I put that somewhere in main the hints prevent resizing (just to be clear, any name for the variable works). It does not matter if I use it at all or not, it was initially there for a call to XGetWindowAttributes. I discovered the problem when I tried moving that into a separate function call. If I take it out, the window will have a full screen button and I will be able to shrink it. I have experimented with declaring the variable other places, such as in the struct where I contain the Window and GLXContext.
What is going on here? The way I see it I either have a very subtle and unusual bug coming from my virtual machine or something weird like that, or I have missed some obvious piece of information. Can anyone shed some light on this?
Well, I have no explanation for why declaring a XWindowAttributes instance in main was making it work, but I did figure out what was wrong with my code and I was able to make it behave as expected when I made the following changes:
Do not create XSizeHints directly as shown above. Create it as follows:
XSizeHints *hints = XAllocSizeHints();
Set flags in the object specifying which variables are used:
hints->flags = PMinSize|PMaxSize;
Use XSetWMNormalHints and XSetWMSizeHints:
XSetWMNormalHints(dpy, win, hints);
XSetWMSizeHints(dpy, win, hints, PMinSize|PMaxSize);
I also put a pointer to the hints in my struct containing data about the window. All together the code above became:
XSizeHints *hints = wind->hints = XAllocSizeHints();
hints->flags = PMinSize|PMaxSize;
hints->min_width = hints->max_width = setup.w;
hints->min_height = hints->max_height = setup.h;
XSetWMNormalHints(dpy, win, hints);
XSetWMSizeHints(dpy, win, hints, PMinSize|PMaxSize);
For those that came here:
1. Communicating with the Windows Manager
It's all about convention like said at 12.3 in the "Xlib Programming Manual VOL1". Some WM will completely ignore hints like max & min size, because eg they manage Windows as Tiled Windows. So, how YOUR Window Manager will get your choices is an issue.
2. Make things in the right order.
This will perhaps answer your question : "What is going on here?"
Most difficulties with X comes from the order you make things. I encountered the same trouble as yours, and solve it because I saw I didn't follow the right process.
Chapter 12.3.1 from the "Xlib Prog Manual" says:
'Once the client has created the windows, BUT BEFORE IT MAPS THEM, it must place properties to help WM manage them effectively'
In your case, it means you cannot use XSetWM* functions AFTER your window is mapped. Some properties will have an effect, some others not, and sometimes some will be overridden with bad values.
3. The right order. (AFAIK)
a. Set an Error Handler
b. Get a Display
c. Init your Context (here GLX) & get a Visual from it.
d. set Window Attributes (events mask, ...)
e. Create your Window
e. Set WM Properties (eg your sizehints, min/max size, class, title, ...)
e.1 always init pointers you need with XAlloc* when possible
e.2 use X11r4 XSetWMProperties that will put them all at once, avoid use of deprecated functions.
e.3 XFree your 'pointers'
f. Set the Wm Protocols you are interested in (WM_DELETE_WINDOW, ...)
g. set some others properties according to your needs (eg _NET_WM_PID, ...)
h. Finally, Map your Window
4. See what happens : use xprop
xprop will report how your window is known by your Windows Manager.
If your size hints were properly set, you will see some lines like:
WM_NORMAL_HINTS(WM_SIZE_HINTS):
user specified location: 550, 200
user specified size: 500 by 500
program specified minimum size: 500 by 500
program specified maximum size: 65535 by 65535
Hope it helps future users,
(PS: the previous answer TS#Oct 27 '14 at 15:26 has an error: XSetWMSizeHints expect an Atom as 3rd arg.).

Add accelerator ctrl+F for text search

I am trying to add a Ctrl+F accelerator to my gtkmm textview program. I already implemented the search function into an gtk Entry field, so the only thing I need is to get focus the find entry when Ctrl+F is pressed.
I googled and checked tutorials/reference of gtkmm (2.4, I'm working with that) but the only things I found were accelerators in context with menus and toolbars using UIManager, which I don't have in that .cc file I use (and I can't add them, cause its an existing program).
I tried to add an action with an AccelKey on a button or tried the function add_accelerator() but I wasn't able to use them properly (I am pretty new to gtkmm and there aren't enough samples - at least none I understand). Here some examples I tried:
_gtkActionGroup->add(
Gtk::Action::create("find", "Find", "search in file"),
Gtk::AccelKey("<control>F"),
sigc::mem_fun(this, &SrcFilesView::onGtkTxtFindAccKeyPressed));
I didn't know how to add this action to the button (in the toolbar) I created...
_gtkAccelGroup(Gtk::AccelGroup::create()) //initialized in the constructor of the class
...
_gtkBtnFind.add_accelerator("find", _gtkAccelGroup, GDK_Find,
Gdk::ModifierType::CONTROL_MASK, Gtk::ACCEL_VISIBLE);
I tried here something, but I didn't really understand neither the parameters I needed to enter here nor how this method works - ofc it didn't work...
I'd be really happy if anyone can explain me how this things work properly and sorry for my bad english. If there are any things you need just tell me please. Thanks in advance
Greetings
edit: I looked up in the gtk sources and tried to understand the parameters of add_accelerator. Now I tried this but still doesn't work...:
_gtkBtnFind.add_accelerator("clicked", _gtkAccelGroup, GDK_KEY_F /* or better GDK_KEY_f ?*/,
Gdk::ModifierType(GDK_CONTROL_MASK), Gtk::AccelFlags(GTK_ACCEL_VISIBLE));
_gtkBtnFind.signal_clicked().connect(
sigc::mem_fun(this, &SrcFilesView::onGtkTxtFindAccKeyPressed));
UPDATE:
Okay I have understood most I think now, and I know why it doesn't work. The problem is that I have to add the accel_group to the window widget, but I got only a scrolled window and boxes in my program....and now I have no clue how to continue... :)
UPDATE2:
Alright I managed to do it without accelerators by using the "on_key_press_event" handler by checking the state and keyval parameter. Hope this helps some ppl at least ^^.
bool on_key_press_event(GdkEventKey* event) { /* declaration in my constructor removed */
if(event->state == GDK_CONTROL_MASK && event->keyval == GDK_KEY_f
|| event->state == (GDK_CONTROL_MASK | GDK_LOCK_MASK)
&& event->keyval == GDK_KEY_F) {
_gtkEntFind.grab_focus();
}
return false;
}
I would be still interested in a solution with the accelerators if there is any ! Greetings

SubclassWindow() function assert

Its c++ developer want to learn more about vc++. :)
One concept called subclassing is one milestone i have. Basically i go through the following article of codeproject Create your own controls - the art of subclassing its interesting and i understand greatly.
But when i execute same with visual studio 2010 i get assertion at following point.
CWnd* pWnd = GetDlgItem(IDOK); // or use some other method to get
// a pointer to the window you wish
// to subclass
ASSERT( pWnd && pWnd->GetSafeHwnd() );
m_OkButton.SubclassWindow(pWnd->GetSafeHwnd()); //Assertion point.
Please note above code is placed in OnInitDialog() function and
I have some similar experiences.
This code seems causing the error
VERIFY(m_Edit.SubclassWindow(parent->GetSafeHwnd()));
Change to this line,everything would be ok.
m_Edit.SubclassDlgItem(nId,parent);

another win32 problem

Having a problem here with creating a child window with c++ and win32 api.
If i check the getLastError function its returning "87" but i dont know what that means.
For what i know my code does not contain errors, can someone take a look at my code and help me figure out whats wrong with it.
(This is in the WinProc WM_CREATE section.)
HWND hChildWindow = CreateWindowEx(WS_EX_CLIENTEDGE,0,NULL,WS_OVERLAPPEDWINDOW|WS_VISIBLE,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,hwnd,0,GetModuleHandle(0),NULL);
if(!hChildWindow)
{
char text[256];
int errormsg = (int)GetLastError();
sprintf(text,"Error# %i",errormsg);
MessageBox(0,text,"Error",MB_OK|MB_ICONEXCLAMATION);
return false;
}
87 = Invalid Parameter - be aware that you can use FormatMessage to get a string message from an error code.
The 2nd parameter to CreateWindowEx is a window class (either string or ATOM). Obviously NULL is not a valid value.
P.S.
For what i know my code does not
contain errors...
Beware of such a loud phrases. When something doesn't work everything should be checked carefully. Otherwise you may just accuse something/someone without any good for solving the problem. Check everything vs standard/documentation/specifications/etc. before you make any judgement.
A quick look through the System Error Codes reference indicates ERROR_INVALID_PARAMETER. You're most likely passing in an invalid combination of styles/flags to your window.

"Debug Assertion" Runtime Error on VS2008?

I'm writing a C++ MFC program on VS2008 and I'm getting this "Debug Assertion Error" when I first run the program sometimes. When I try to debug it, it takes me to this winhand.cpp file which is not part of the program I wrote so I'm not sure how to debug this.
It takes the error to this place in winhand.cpp
CObject* pTemp = LookupTemporary(h);
if (pTemp != NULL)
{
// temporary objects must have correct handle values
HANDLE* ph = (HANDLE*)((BYTE*)pTemp + m_nOffset); // after CObject
ASSERT(ph[0] == h || ph[0] == NULL);
if (m_nHandles == 2)
ASSERT(ph[1] == h);
}
So why does this error happen? Why does it only happen sometimes (50% of the time)? How would I debug this?
I'll provide some code if is needed.
THANKS!
The code that is asserting is part of MFC's CHandleMap class. MFC deals with windows as CWnd objects, but Windows deals with them as HWND handles. the handle map allows MFC to 'convert' an HWND into a pointer to the MFC object representing that object.
What the assertion seems to be doing is checking that when a lookup of the handle finds an MFC object, that the MFC object also thinks it's wrapping the same handle.
If they're different, then you get the assertion.
So it would appear that something is corrupting the handle map or the MFC object for that handle or you're doing something incorrect that gets these 2 data structures out of sync.
Some things you might do to try to debug the problem is to determine:
what MFC object is being found in the lookup (that's what's being pointed to by pObject)
what the MFC object thinks it's wrapping (that's the handle ph[0] and/or ph[1] - I'm not sure why there can be 2 of them)
what the handle is for (that's h)
Do the handles look like handle values or do they look like garbage? Does pObject point to something that looks like an MFC object, or garbage? Do any of these these things seem related?
The answers to these questions may point to what you need to do next (maybe set a debug write breakpoint on the item that looks like it's trashed).
I got this same assertion few days ago, and after some google search,
I found the solution for my case here:
http://forums.codeguru.com/showthread.php?216770-What-would-cause-this-assertion
In my case, change to misused
CDC* dc = GetDC();
CSize spaceSize = dc->GetTextExtent(" ");
dc->DeleteDC();
to
CDC* dc = GetDC();
CSize spaceSize = dc->GetTextExtent(" ");
ReleaseDC(dc);
would fix it.
Look out for code along those lines (from memory from Stroustrup's book):
c1 = (t2+t3).c_str();
(in spirit, could be other commands and expressions of course).Temporary objects are destroyed after their enclosing full expression has been evaluated, or at least the standard allows them to be. That means that what you would like to allocate to c1 may, or may not, still be in memory where it can be assigned to c1. The compiler may alert you to this issue, and the issue may or may not arise depending on what exactly you assign and other circumstances (I am not compiler writer), which would also explain why you get this error message only sometimes.
So in your shoes, I'd scan my code for similar expressions and clean them up.
When the debugger breaks, head up the call stack to the first bit of your code (if there is any - hopefully there is!). Ideally it's as simple as something in your code calling a library function incorrectly, and the library is catching the error with an assert and alerting you to that. (I don't think anyone will be able to tell what's wrong from the library code, we need to see your code.)
Otherwise, you're in for some tricky debugging: you're doing something wrong with the library that is asserting (looks like MFC) so go back and review all your MFC code and make sure everything is correct and according to the documentation.
This looks suspiciously like an error I had this morning. Is this happening in OnIdle()?
I know this is a very old post, but hoping that someone may get a little help from my answer.
I also faced a similar issue recently because of my simple mistake, then I came across this post and got a hint from "pac"'s post.
What I found is that if I use DeleteDC() to release DC returned from GetWindowDC() or GetDC() I will get the above assertion in MFC frame once CPaintDC object instance goes out of scope.
CDC * pDC = GetWindowDC();
...
ReleaseDC(pDC);
You have to use DeleteDC() only in conjunction with CreateDC() API.
CDC * pDC = new CDC();
pDC->CreateDC();
....
pDC->DeleteDC();
We had this problem when some of our project dlls were linking MFC as static library and some as shared library (check "Use of MFC" in Project settings)