Weird Fault on GetFocus

Hey. I keep crashing on this code blip (quite randomly) and can't seem
to track why or a fix around.

CWnd *activeSelected = GetFocus();
if (activeSelected->m_hWnd != NULL)	{  .. Fault occurs here

I'm not sure what the reason is, but it might happen once every 2-10
minutes, and i'll have several windows open and a few dialog boxes open
from the application. But every time I get a fault, it returns back to
the same line of code (!= NULL) bit..

And also,

CSomeDlg *dlg; (a Member variable in another dialog)

Say in a button press for a modeless dialog window.

if (dlg) {
delete dlg;
}

dlg = new CSomeDlg;
dlg->Create(IDD_...


the 1st section runs fine and does what's required (only allow one
modeless dialog of that dialog class on a certain button press)  and I
get no problems with it, BUT If i try to debug with that code block
running, VC7 gives me an error and causes the debugger to halt.

So I figure I'm doing it wrong, any of you aware of the proper
procedure.

Thanks

0
sirkaber (8)
12/27/2005 10:03:26 AM
vc.mfc 33608 articles. 0 followers. Follow

4 Replies
650 Views

Similar Articles

[PageSpeed] 47

"sirkaber" <sirkaber@gmail.com> wrote in message 
news:1135677805.963988.71010@z14g2000cwz.googlegroups.com...

> Hey. I keep crashing on this code blip (quite randomly) and can't seem
> to track why or a fix around.
>
> CWnd *activeSelected = GetFocus();
> if (activeSelected->m_hWnd != NULL) {  .. Fault occurs here

A better idea would be:

if ( activeSelected && ::IsWindow( activeSelected->m_hWnd )  )
{
}

This is safe if  GetFocus returns NULL  and if it returns a CWnd * which has 
no window attached.   I am not sure that the latter should be possible - so 
call it "defensive programming".   Otherwise it may be something in the code 
you don't quote.

> if (dlg) {
> delete dlg;
> }

Check out the DestroyWindow() API.

You have to remember that MFC is basically *not* object oriented.  Having a 
CWnd does not mean you have an actual window: that depends on its m_hWnd 
member.   It is quite possible to have CWnd's floating about all over the 
plavce with no actual windows.   The CWnd is just a wrapper around an HWND 
so that you can use C++ syntax to address it.    The CWnd constructor does 
not create a window; the destructor can call DestroyWindow() but looking at 
the source code it looks rather conditional!

Dave
-- 
David Webber
Author MOZART the music processor for Windows -
http://www.mozart.co.uk
For discussion/support see
http://www.mozart.co.uk/mzusers/mailinglist.htm


0
dave1 (356)
12/27/2005 11:53:20 AM
The problem is that you have not tested the pointer itself for NULL.  If no window has the
focus, then GetFocus will return NULL, and your attempt to dereference it will, as you
indicate, crash.

Generally, the way to do this is

CWnd * activeSelected = GetFocus();
if(activeSelected->GetSafeHwnd() != NULL) { ...do something...}

You made the mistake of checking m_hWnd being NULL, which is erroneous.  You need to check
if the pointer itself is NULL.  Note that GetSafeHwnd(), if the pointer being dereferenced
is NULL, returns NULL without trying to dereference it to get the m_hWnd.

Actually, MFC *is* object oriented.  However, objects have *state*.  A CWnd object has a
state of not having a window, and a state of having a window, and you must distinguish the
two states. 

A CWnd-derived class constructor might or might not create a window (that is up to the
implementor).  However, constructors for CWnd and the standard classes do not create
actual windows, they create CWnd objects in the state of having no window.  You later
operate upon these objects with methods like Create or DoModal to change their state from
having no window to having a window.

The construct
if(dlg)
    delete dlg

is a bit silly because the delete operator is defined to work correctly if the object
points to NULL.  Also, I find it strange to treat pointers as boolean values; I consider
this sloppy programming.  If you want to see if a pointer is NULL, you should write ==NULL
to make it clear what is going on.
				joe

On Tue, 27 Dec 2005 11:53:20 -0000, "David Webber" <dave@musical.demon.co.uk> wrote:

>
>"sirkaber" <sirkaber@gmail.com> wrote in message 
>news:1135677805.963988.71010@z14g2000cwz.googlegroups.com...
>
>> Hey. I keep crashing on this code blip (quite randomly) and can't seem
>> to track why or a fix around.
>>
>> CWnd *activeSelected = GetFocus();
>> if (activeSelected->m_hWnd != NULL) {  .. Fault occurs here
>
>A better idea would be:
>
>if ( activeSelected && ::IsWindow( activeSelected->m_hWnd )  )
>{
>}
>
>This is safe if  GetFocus returns NULL  and if it returns a CWnd * which has 
>no window attached.   I am not sure that the latter should be possible - so 
>call it "defensive programming".   Otherwise it may be something in the code 
>you don't quote.
>
>> if (dlg) {
>> delete dlg;
>> }
>
>Check out the DestroyWindow() API.
>
>You have to remember that MFC is basically *not* object oriented.  Having a 
>CWnd does not mean you have an actual window: that depends on its m_hWnd 
>member.   It is quite possible to have CWnd's floating about all over the 
>plavce with no actual windows.   The CWnd is just a wrapper around an HWND 
>so that you can use C++ syntax to address it.    The CWnd constructor does 
>not create a window; the destructor can call DestroyWindow() but looking at 
>the source code it looks rather conditional!
>
>Dave
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15975)
12/27/2005 4:24:09 PM
"Joseph M. Newcomer" <newcomer@flounder.com> wrote in message 
news:42q2r1tq66l9975cpgln9vojn7tfl5ufif@4ax.com...

> Actually, MFC *is* object oriented.  However, objects have *state*.  A 
> CWnd object has a
> state of not having a window, and a state of having a window, and you must 
> distinguish the
> two states....

I find this simply a semantic obfuscation.   Describing a CWnd as an object 
(of some kind) which may or may not "have" a window is of course one way of 
looking at it.  But in that case almost anything can be described as being 
object oriented - all you have to do is define your objects so that it 
becomes so.

A CWnd is an object which represents a thin wrapper around a subset of the 
Windows API.   If the API is an object than the CWnd is one.  But this is 
not what is normally described by "object orientation".   In the traditional 
sense, "constructing" a CWnd with "CWnd x;"  gives you a non-object: an 
object wihich has not been created.  This is acknowledged by the name of the 
method which does create an object:  CWnd::Create().

Other aspects of MFC display an equal lack of object orientation - for 
example the standard application framework where a "view" of a document is 
created before the document itself.

Please note that I am attempting to be factual rather than to criticise 
here: I am not attached to object orientation any further than the fact that 
it serves a useful purpose, and I regaularly do things which would cause 
*some* OO purists to chastise me (including lashings of multiple inheritance 
and occasional mutable data members).

> The construct
> if(dlg)
>    delete dlg
>
> is a bit silly because the delete operator is defined to work correctly if 
> the object
> points to NULL.

IIRC it was not however always so in Microsoft C++.    Personally I find 
that the if(dlg) but will often serve as a reminder to me, when I'm 
reviewing code, that it may in fact be NULL.

> Also, I find it strange to treat pointers as boolean values; I consider
> this sloppy programming.  If you want to see if a pointer is NULL, you 
> should write ==NULL
> to make it clear what is going on.

No.   This is simply a matter of personal preference.  if( expression ) is 
defined by the C++ language standard when "expression" is an integer, a 
pointer, or  anything which admits a cast operator (eg) to an integer.

NULL  IIRC is not actually defined by the C++ language standard - it is 
#defined as zero in the Windows headers.  Comparing a pointer with an 
integer is no less sloppy than relying on the language standard for if(), 
and relying on the existence of NULL is actually (if I'm right) less 
portable.   The difference is of course utterly trivial and I sometimes 
write if( pointer==NULL ) just as I often write if( pointer ).   As, over 
the years, I have become more and more familiar with C++, I find myself 
using the if( pointer ) construct more and more often: it is more compact 
and does not distract so much from the other bits of code around it.

Dave
-- 
David Webber
Author MOZART the music processor for Windows -
http://www.mozart.co.uk
For discussion/support see
http://www.mozart.co.uk/mzusers/mailinglist.htm




0
dave1 (356)
12/27/2005 7:15:43 PM
Thanks for the quick code fix on how to fix the somewhat random
crashes. That problem with the GetFocus issue looks to be resolved.

>is a bit silly because the delete operator is defined to work correctly if the object
>points to NULL.
Indeed..
This is what I do but the debugger will still halt the program when it
hits this code block.
But runs fine when the debugger is not run to launch the application.

// just want to make sure it doesn't have multiple of these windows
opened up.
// only the most recent one when the button is pressed.
if (dlgSomeDlg)	{
	dlgSomeDlg->DestroyWindow();
	delete dlgSomeDlg;
}

dlgSomeDlg= new thatDlg;
dlgSomeDlg->Create(IDD_DIALOG, GetDesktopWindow());

Not entirely sure the proper way to do this.

0
sirkaber (8)
12/28/2005 10:15:06 AM
Reply:

Similar Artilces:

Weird Parameter Passing Bug
I have the following classes : CTestBase CLogic (virtual class, derived from CTestBase) CScanLogic (derived from CLogic) CBacktestLogic (dervied from CLogic) I instantiate a CScanLogic object which takes 3 CStrings, and a CStringArray as parameters. The prototype looks like this : CScanLogic (CString &x,CString &y,CString &z,CStringArray &a); The members variables are protected variables residing in the CTestBase class. They are CString m_x,m_y,m_z; CStringArray m_a; CScanLogic::CScanLogic (CString &x,CString &y,CString &z,CStringArray &a): CLogic(x,y,z,a...

Weird Behavior
Excel 2007. I've created a simple spreadsheet with various data. I save it and close it out. When I opened it this morning, the data in four of the columns said 12:00 am instead of what I had entered previously. This has happened several times now, and I'm at a loss as to what is happening.. ...

Fault tolerance needed
Hi everybody - I work at a bank and we are running GP 10 and SQL 2005. We need an offsite fault tolerance solution - in the event that our site goes down [fire, water or natural disaster], we need to be able to have a duplicate GP/SQL server up to date with and the latest transactions at another location. We are in NJ and the other site will be in NY. What solution would you recommend? Michael, In this scenario, You can look at SQL Server Log Shipping method. GP supports Log Shipping and Replication as well. I'd suggest you to go through the KB Article 926490 that talks about...

Invalid page fault in module RPCRT4.dll
Dear all, I'm using Windows 98. I have the following error message : MSACCESS caused an invalid page fault in module RPCRT4.DLL at 0187:7fbd0894. Registers: EAX=0063350b CS=0187 EIP=7fbd0894 EFLGS=00010216 EBX=0062f3d0 SS=018f ESP=0062f1f0 EBP=0062f3e0 ECX=7713ee58 DS=018f ESI=00000484 FS=4e8f EDX=bff76855 ES=018f EDI=7713ef6e GS=0000 Bytes at CS:EIP: ff 30 ff 75 d4 8d 85 1c fe ff ff 50 e8 cb 0b 00 Stack dump: 0062f714 00000000 00000000 0062f338 bff7a3a0 00000000 00000000 000ebf94 00000000 0040000c 00400000 00000001 00000000 00000000 8c7e07e0 00000000 Another error message : MSMSGS caus...

Weird error messages all of a sudden
I have a user getting weird error messages that didn't used to come up. They don't come up on my machine. I have Office 2003 and he has Office 2000. My database is in Access 2000 format. The messages:1.) The field is too small to accept the amount of data you attempted to add.2.) The select statement uses a reserved word or an argument name that is misplaced or missing.In each case these messages are coming up when the user tries to open a form that refers to about 100 fields and has selection criteria such as type ="B" or Name <>"Brown". In one case th...

FA Manager* Security Setting Is Weird
Hi, I found out the security setting in V10 is working werid... For example, there is a predefined Role called "FA Manager*". Its description states that this role can do everything for FA management. However, when I looks at the securtity tasks under this role, there is no task that actually say that this role can do "Retire Asset". The most possible task would be "TRX_FIN_FA01", but it does not contain any windows relating to retiring asset. But the user with the FA Manager* role assigned CAN retire the asset. I don't how this can ...

Outlook Caused General Protection Fault In Module GDI.EXE #2
at 0001:00001810 I have labtop, using Windows 2000 ME and Microsft 2000 office suite for small business. Have 320K memory. Do i need to purchase the new xp operating system and the new office applications??? Thanks you for any help, You would be better off purchasing new hardware - faults in GDI are usually a sign of a hardware failure about to happen. --� Milly Staples [MVP - Outlook] Post all replies to the group to keep the discussion intact. After searching google.groups.com and finding no answer: Craig <kucraig@swbell.net> asked: | at 0001:00001810 | | I have labtop, usin...

DB Conversion Results in Weird Printing Problems
I was recently upgraded to Access 2000. Now, several DB applications I had built no longer print reports and shut down the apps. Furthermore, they wipe out the printers that are listed in "start/settings/printers" before I run the databases. Trying to add them back leads to a "lack of resources" error. I have to reboot to get them to show up again. Weird, huh? Other, very complex VB code works fine however. Any advice from gurus out there? ...

loan split info weirdness
Hi, not sure how to describe this problem as I am not sure where it is occuring so I will attempt to be as detailed as possible. I have a payee for my mortgage payments and have about 10 transactions listed that are not split and showing the calculated priciple amounts (those that are split are numbered 1 to 50, the ones causing grief are unnumbered). This payee is listed of course in a loan I have an asset listed as my house with the aforementioned loan associated with it. When I go to the associated loan account for this asset all of the payments show with their associated breakdo...

MSMONEY caused a general protection fault in module [ ]
This is happening in MSMoney 99. I cannot print because every time I try, I get the subject error. In my specifc case the module was LXBKXC.DLL. I have tried reloading Money and my printer drivers, of which the DLL is one file. Does anyone have any experience with this? Dont have experience with that file, but with the error in general. First question is what OS are you using?? Usually errors like these are hard to track down, could be caused by a number of things. A recently loaded program is a good place to start. "Jack" <Jack@discussions.microsoft.com> wrote in mess...

weird outlook 2007 shutdown problem
I run Outlook 2007 on Windows XP Pro SP2. When I reboot my computer ... the first time I start Outlook and go to close it ... It still runs in task manager. It doesn't use any CPU time so normally I would just say the heck with it but .... it does use anywhere from 66M to 127M of ram and I noticed when if I continue to let it run it slowly uses more and more ram... I can open and close it as many times as I want yet it still runs in TM. I have to end task on the process to get it to shut down .. Once I have ended task on the processes and launch Outlook again ... when I close it .. ...

ErrorMessage: SOAP Server Application Faulted 80040225: Specified user disabled
I've created an ASP.NET page that uses the Microsoft.CRM.Proxy.dll to retrieve Contact details from the CRM database. The page is launched from a csutomised menu om the Contact form in the CRM and the Contact GUID is posted to it. I keep getting the following error when I run the page: ErrorMessage: SOAP Server Application Faulted 80040225The specified user is either disabled or is not a member of any business unit.d:\mscrm\build\3017\src\platform\security\crmsecurity\secmain.cpp2029 Source: System.Web.Services When I run the page I'm logged onto the CRM as a valid business user as ...

Outlook acting weird
Recently I had a problem with exporting my outlook pst file. I had to go back into the setup and add the export feature. Since then I had a problem with outlook not wanting to sync with my pocketpc. I read some knowledgebase files and am at a point where I can now sync my calandar, contacts and tasks but CANNOT sync my inbox. The error I get is "Attention Required" and I cannot do anything with the inbox at all. Any suggestions would be greatly appreciated. Also...on the Outlook today main page I cannot customize Outlook any longer. I push the button at the top right to change the ...

MSIMN caused an invalid page fault in module DIRECTDB.DLL
This is the error message I keep getting when using OE 6 on my Windows 98 system. Any ideas how to fix? Thank you. Laura ------------------------------------------------------ MSIMN caused an invalid page fault in module DIRECTDB.DLL at 017f:019e6bb1. Registers: EAX=00000000 CS=017f EIP=019e6bb1 EFLGS=00010246 EBX=01c5d234 SS=0187 ESP=01c5d088 EBP=01c5d240 ECX=00000000 DS=0187 ESI=01a0b5dc FS=4f9f EDX=00000000 ES=0187 EDI=800c0131 GS=0000 Bytes at CS:EIP: 83 78 60 00 75 07 8b ce e8 d9 e4 ff ff ff 76 0c Stack dump: 00000000 01672250 007df27e 01a0b5dc 01c5d234 007e01ea 016720b0 01c5d234 007d...

Weird GDI leak
Hi! I'm using VC++ 6.0 to make a flowchart graphic editor, i'm using win2k SP4. All was fine, but i run my app in win98 and it crashes showing an out-of resources message when i scroll my childview. I'm using a generic CWnd has childview and i use my own coordinate system to emulate scroll using negative y-values, i'm using devparter to find the leak but it doesn't report anything... Thanks! In message <61A1D4EF-0CCB-46F9-AB1F-2F370FE7587D@microsoft.com>, Extrange GDI leak <Extrange@GDI.leak.invalid> writes >All was fine, but i run my app in win98 and ...

Strange Publisher 2003 fault
Hi, Here is a description of a fault I am experiencing with Publisher 2003 - clean install and fully patched on Windows XP Pro. You select a block of text and increase the text size ( ctrl + } ) as a word reaches the end of the text box rather than auto-hyphenate or go to the next line it 'wraps' letter by letter until the whole word is on the next line. Any suggestions? TIA, Bart. I can't duplicate your fault. Maybe you are using a strange font, in any event it isn't a big deal. -- Mary Sauer MSFT MVP http://office.microsoft.com/ http://msauer.mvps.org/ news://msnews.m...

Weird files created in root folder when downloading mail
Recently I've been getting weird files in the root of drive c whenever I open Outlook 2003 and start downloading mail. Today the files are named s3us.x where x is 1 to 9 and a to v then starting over with 11. For example: s3us.1 s3us.2 s3us.3 .... s3us.9 s3us.a s3us.b .... s3us.v s3us.11 s3us.12 The files cannot be accessed while outlook is open. After closing outlook I still couldn't access my mail and took a guess and killed ccApp.exe. After killing that program I was able to access the files. I've opened a few files with text editors and the contents resembles my mail. Any...

Getting weird e-mails
I'm getting messages saying that a message sent is undeliverable, however I never tried to send the message. I went to look at its details here's what I found. Received: from ocwjgi (eatkyo410131.adsl.ppp.infoweb.ne.jp [220.145.135.131])by userg503.nifty.com with SMTP id j987Fms8030866; Sat, 8 Oct 2005 16:15:48 +0900 Authentication-Results: userg503.nifty.com from=masterrobot@netmail.com; sender-id=neutral; spf=neutral Date: Sat, 8 Oct 2005 16:15:48 +0900 Message-Id: <200510080715.j987Fms8030866@userg503.nifty.com> FROM: "Postmaster" <masterrobot@netmail.com>...

clear circular reference fault?
I have a worksheet with a number of circular references. I have iteration turned on, and it seems to do what I want. But, if I make some particular mistakes (eg: entering really unreasonable data), I get into a situation where most of the cells are #VALUE. The only way I've found to clear this is to re-load a good copy of the sheet. 'Undo' has no effect. Are there better ways to recover from this? More generally: my knowledge of Excel is kind of spotty. I don't have the time to become expert in Excel, but sometimes I want to use some particular more advanced feature. The...

Weird "Undeliverable" Notification from deleted user?
All, I'm having this weird problem when I try to set up a appointment with only this one user. I get a "Undeliverable:Delivery Status Notification" from a deleted user(user no longer works for company) that the user does not exist. I made sure i only select the user and no one else. >From my understanding the "deleted user" used to be that person assistant, and I guess they did a forward to her that whenever someone try to make an appointment to this user, the assistant can approve or not approve the appointment. Now, I search for the "deleted user" na...

Weird problem
Hi everyone - Last weekend, OL2003 started having problems staying connected to my IMAP server (I do not use exchange). Suddenly, it would only download the headers, but not the messages. When I mark those messages to download, OL tries several times (within a few seconds of each try) to update the cached headers and then says the request could not be completed by the IMAP server before the connection was terminated. I have unloaded the entire Office 2003 Prof install, and then reinstalled. Same thing happens. I discovered that if I delete the email account and the profile (including the ....

Weird OWA Problem
Hello, Exchange 2003 & OWA has been working for quite some time and as far as I remember I've made no config changes. All of a sudden, when users hit the "LOGOFF" button in OWA it says that it cannot find this page: <server path>/exchweb/bin/USA/logoff.asp I get a 404 error as though the file does not exist. HOWEVER, I've manually checked and the directory & file is indeed there! What is causing this? How do I even go about debugging this? Has anybody else come across this problem? please help, thanks! ZD Hello, Thanks for your posting here. Based o...

Outlook Hang: Fault bucket 262152128
Anyone have any idea what this error message means? My outlook suddently hang this afternoon, an hour after I've installed Google Desktop (not sure if it's related). I have no way to get Outlook going, even safe mode failed, and "detect and repair" doesn't fix the problem. An idea? Does uninstalling Google Desktop change anything? --� Milly Staples [MVP - Outlook] Post all replies to the group to keep the discussion intact. All unsolicited mail sent to my personal account will be deleted without reading. After furious head scratching, cn649@torfree.net asked: | A...

Recipient update weirdness for policies, mailbox management actions
One of my questions will be whether I can anticipate any changes in 2003, with respect to the issue below. Situation: One exchange server, domain integrated Build 6249.4 SP3 Mailbox management running briefly each evening, sending me a report Recipient update services "always run" Four recipient policies: - User addresses (I'm not sure why my colleague set this up; it's much like the default but with a much more specific filter) - IP literal with brackets (for RFC compliance, as I recall) - Clear junk, deleted folders (this is the one at issue in this post) - Default poli...

Losing scroll functionality
Hello, I am running a workbook that is shared by a few users. Occasionally, we lose the side (up & down) scrolling function and we have to close the workbook and reopen it and then everything is fine. I think this may be link to using filters, but I can not narrow down the exact cause. Has anyone had this happen to them? What is the cause? How do I fix it? Any help or ideas would be great. Thanks, > Hello, > I am running a workbook that is shared by a few users. Occasionally, we > lose the side (up & down) scrolling function and we have to close the > workbo...