Crash after the second RichEdit initialization in x64 - windows

According to Using Rich Edit Controls I use RichEdit in such way:
MyControl::OnCreate()
{
handle = LoadLibrary(_T("Riched20.dll"));
}
MyControl::OnDestroy()
{
FreeLibrary(handle);
}
It works fine for win32 but recently I’ve built x64 configuration and now my control fails after the page reload.
I’ve noticed that if do this:
MyControl::OnCreate()
{
handle = LoadLibrary(_T("Riched20.dll"));
FreeLibrary(handle);
handle = LoadLibrary(_T("Riched20.dll"));
}
everything works fine.
I don't wish to put this code into production, so is there any suggestions about better solution/workaround?

Since the reported fault module is Richedit20.dll_unloaded it means you are unloading the DLL while code from it is still in use.
For example, if you still have a richedit window open when you (completely) free the DLL, you can see crashes like that as soon as anything triggers a call to the control's window-proc. This is because the control's window-proc was inside the unloaded DLL code.
It should be safe to call LoadLibrary and FreeLibrary multiple times (so long as the calls balance out), so I doubt that is the problem. It may just be triggering the problem. Also, the problem was there in 32-bit builds; you just got lucky and never triggered it.
OnDestroy is the wrong place to call FreeLibrary. There are several window messages which get sent to a window after WM_DESTROY (e.g. WM_NCDESTROY).
Child windows also still exist when OnDestroy is called. If the richedits are children of your control (rather than the control itself) then moving the FreeLibrary into OnNcDestroy may save you. (Child windows are destroyed by the time WM_NCDESTROY is called.) I'd still say it's not a good place to free the library, however.
So you definitely want to move your FreeLibrary call. I would move both it and the LoadLibrary completely out of the control itself. It's not normal to have controls which load/free libraries whenever an instance of them is created. Instead, have some static init/uninit code somewhere which loads the libraries you need once and for all and frees them when the application is shutting down.
(If your app only rarely uses the control then it might make sense to load/free the library only when windows using the control are active. That situation is rare, though. Usually you're better off just leaving the DLL loaded.)

Related

CMFCToolbar ReplaceButton() causes button to disappear

Using Visual Studio 2010 and working with an MFC SDI Application.
I have a CMFCToolbar object owned by the Main Frame.
When the document in this application is created, the MainFrame calls a function to replace one of the buttons in the CMFCToolbar object with a CMFCToolbarMenuButton. The contents of the menu button are populated with information from the document. The menu creation always works. The call to ReplaceButton always succeeds. But there's a visual symptom of the call that I haven't yet figured out.
Any time ReplaceButton is called, the button disappears. Not only is it not drawn, it's not clickable. It's temporarily gone. I assume this is because there's a dangling reference to the old button, which I have just destroyed with the call to ReplaceButton.
I've tried calling Invalidate(), RecalcLayout() to trigger a re-draw, but neither has worked yet. The only reliable method I have for getting the button to show up is re-sizing the application window manually or by un-docking/re-docking the toolbar. I assume there's some kind of lower-level refresh that occurs in these situations, but I don't know how to trigger it manually.
Is there a way to make sure my button is drawn immediately?
Edit: code sample
Count = m_Doc->...->GetCount();
for (Index = 0; Index < Count; ++Index)
{
Caption.Format(L"%s", m_Doc->...->GetName());
m_pLayerMenu->AppendMenu(MF_ENABLED | MF_STRING, LAYER_DROP_SEED+Index, Caption.GetData());
}
m_wndBrushBar.ReplaceButton(ID_BRUSH_TERRAIN,
CMFCToolBarMenuButton(ID_BRUSH_TERRAIN, *m_pLayerMenu, GetCmdMgr()->GetCmdImage(ID_BRUSH_TERRAIN)));
Update:
Calling m_wndBrushBar.AdjustLayout() seems to stabilize the visual behavior of these CMFCToolbar buttons. So that's a partial solution.
Partial because of the following:
It's hard to tell what the real visual behavior is. It turns out that all visual settings/states are stored in the Registry with these MFC objects, and it can hold onto states of dynamically created objects that really alter the startup behavior of the app.
I've gone in to delete the registry values under
Current User -> "Local App-Wizard Generated Applications" -> [My App Name].
Done this a number of times, just to find out what the real behavior of my app is. Feel like I'm missing some fundamental knowledge with the current version of MFC. Lots of bugs arising from the registry deal.
Is there a way to prevent registry settings for certain objects, or to shut off this behavior altogether? Otherwise, I guess my shutdown process will have to be a LOT more thorough with resetting all the visual elements. Registry values seem to ignore, override, or bypass my startup code. I can code how I want an object to look at startup, but if there are values in the registry, it does no good.
You've discovered a sometimes annoying aspect for the CMFC code. That is, the concept of a Workspace. The Workspace manages the concept of the application state. I, too, have had problems like the one you describe. But, you have the flexibility to manage how those objects are recreated by overriding the LoadState () and SaveState () methods.

How to avoid crash in MFC SDI application caused by unloaded comdlg32.dll?

We have an application built against MFC9 (VC2008).
The application is an SDI application, and shows a file open dialog during InitInstance(). Showing that dialog causes comdlg32.dll to be loaded. Some minutes later, the comdlg32.dll is unloaded automatically. After this, the next function depending on the DLL will crash.
How can this be avoided? What governs the automatic unloading/loading of the DLL?
Further info:
We don't see this problem on WinXP with the same application.
On Win7, this behavior only occurred since the beginning of this year - maybe some MFC update is related to this?
A small test application does not exhibit the problematic behavior - the comdlg32.dll is re-loaded when needed.
We’ve found a statement by Microsoft that it isn’t recommended to use modal dialogs in InitInstance() of MDI applications (http://support.microsoft.com/kb/173261) - we have an SDI application, though.
We don't directly use comdlg32.dll in any way, only indirectly through the MFC.
You have to call InitCommonControlsEx in your application on startup.
This will initialize the comdlg32.dll and also increase the reference count of the dll, so it won't get unloaded after closing a file-open/save dialog.
You don't say whether you customize your dialog or it is just a straight up file dialog. I think starting with Vista, the common file dialog was changed some. I know if you compare older MFC code with newer, you will see that the MFC code has been changed to take advantage of those changes. For instance, the IFileDialogEvents and IFileDialogControlEvents were implemented in MFC to support the way Vista and later versions of the OS customize file dialogs.
I don't know if I have an answer, but just for grins I would probably make sure I call AfxOleInitialize() sometime in InitInstance() before I tried to call the file dialog.
The other thing I would try for sure (since it works under XP) would be in the constructor of your CFileDialog would be to make sure to set bVistaStyle to FALSE. This ensures m_bVistaStyle is set to FALSE which it is set at when running under XP.

Detecting creation of a MessageBox

My application is loading 3rd party DLLs, and some of this DLLs open MessageBox windows.
Is there a way for me to detect when such a window was being opened?
You'll need a CBT hook to receive a notification when a MessageBox window is displayed. You install this by calling the SetWindowsHookEx() function and specifying WH_CBT for the hook ID parameter. The hook callback function will provide you a handle to the MessageBox window, which you can then use to close it.
If you know exactly when to expect the MessageBox is being created and shown, then you can adopt a lighter and simpler approach than a global hook. This would involve calling the FindWindowEx function to get a handle to the MessageBox window, which you can likewise use to close it.
Of course, to close it properly, you will need to know which type of MessageBox it is (that is, which of the standard button choices that it displays) so that you can simulate a click of the desired button. Simply managing to get the MessageBox to disappear off of the screen without providing a valid answer is highly likely to have unexpected results in terms of the library code.
It bears explicit mention that this is really bad behavior on the part of a DLL. Unless absolutely necessary, ditch whatever 3rd party that is foisting such poorly written code upon you. If it is absolutely necessary, well then that's a red flag: work hard to eliminate it as a necessity. You shouldn't have to write and maintain gobs of code to work around their inability to get the big obvious things right.

IsWindow(activeX.GetSafeHwnd()) always false after upgrade to VS2010

I have an MFC application that uses an ancient (circa 1999) third-party ActiveX control.
Since upgrading the project from VS2008 to VS2010, I'm having problems...
In the OnSize handler of the parent dialog IsWindow always returns false for the handle returned by control.GetSafeHwnd(), even when GetSafeHwnd() returns a non-NULL value. The rest of the control's parent dialog is displayed fine, but it doesn't seem to respond to any input.
I've seen this article, but GetSafeHwnd() isn't returning NULL in this case (after the first time that it is called, which is before the control is instantiated).
The control does cause the trace message "Control wants to be windowless" to be output when it's loaded. However it also does this when compiled in VS2008, so this may be a red herring. Searching for this message points me to creating a class derived from COleControlSite, and denying the control windowless-ness, but it seems there are no good example of this available, and as I say, it's not clear that this is really the cause of the problem.
I've also found this issue mentioned on MSDN's VS2010 porting page:
"An ActiveX control compiled by using Visual C++ 6.0, when embedded in
a dialog box in a project developed by using Visual C++ 2010, may
cause your program to assert at run time. In this situation, open the
ATL or MFC project associated with the ActiveX control in Visual C++
2010, and recompile it.. The assert will be in the file occcont.cpp,
on this line in source: ASSERT(IsWindow(pTemp->m_hWnd))."
I assume that there's something about VS6-compiled ActiveX controls that causes the window handles to be treated as invalid by the current Win32 implementation of IsWindow. The suggested solution is of course unhelpful as it's a third-party control, and we can't recompile it.
Has anyone managed to get around this?
I've already found solutions for VS2010 projects not running on Windows 2000, and errors linking to ODBC, but don't seem to be able to find anything on this one.
Thanks,
Chris
I didn't find a solution to this in the end - upgraded the controls to a VS2010-compatible version.
For what it's worth: if you don't care whether the control will appear transparent or not, you may force the control to have a window anyway - even though it can operate without a window.
You see, the ActiveX control must first ask the container (the window which will host the control) if it's okay to be activated without a window. This is simply because not all containers support windowless activation.
If this interface (IOleInPlaceSiteWindowless) returns okay then it proceeds with this special windowless activation, if not a window will be created for the control as normal.
Disclaimer:
I don't know if this 'unnecessary' window will make the assertion failure go away. In other words: I don't know if the window handle is passed down 'deep' enough into the AX control.
More about the IOleInPlaceSiteWindowless interface:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms682300(v=vs.85).aspx

Subscribe to Vista Events in .NET (e.g. Window Opened)

I am trying to build my own little toolbox for Vista.
One of the features is a "window placeing tool" which places the windows at saved position. Another tool I could imagine are extensions to firefox or thunderbird...
For these tools to work, I need them to be able to capture "Events" in Vista.
To give you a concrete example:
Explorer Opened New Window
User started Firefox
Mouse moved
For the mouse case, there are some examples for C#.
I also know about the directory watcher, nice little helper.
Want I now need is the "new window opened event"
Any idea how to monitor this, without iterating the current window list every 5 seconds (I already know how to get Windows using the DLLImports, and getting Processes using managed code. But I have no Event when the explorer process opens a new windows)
Thanks for your help,
Chris
What you're talking about doing is not simple by any stretch.
You're going to need to register a hook, and you're going to have to build a callback procedure that gets called within another process's execution context -- this is not going to be .NET code (probably C instead), and will have to be in a DLL. That callback procedure will get called every time a certain class of events happens. It will examine the events it receives and filter out the ones you're interested, then send your application the notifications you want (probably via PostMessage). You'll then tap in to your application's main message loop to intercept those messages, and from there you can fire a .NET Event, or whatever you want.
Writing hook callbacks is tricky stuff because the code gets run within another process, not your own, and the memory management and concurrency issues take a bit of forethought. For that same reason, it's not going to be done in C#. Ideally, though, this callback code will be very small and very fast, since it's going to get called so often.
Also note that while perfectly "legal" in Win32, these system hooks have an immense amount of power and are commonly used by malware to change the way your system works. For that reason, you may run afoul of antivirus software if you attempt to do this sort of thing on a customer's computer.
Also note that the far-reaching effects of system hooks also means that simple programming mistakes can take down your whole system, which you will probably discover for yourself at some point while debugging; so save everything before you hit "run".
Good luck!
EDIT
Did a bit more search to see if there's any way to write the hook proc in C#, and came up with this:
How to set a Windows hook in Visual C# .NET
This is almost what you're looking for, but not quite. Hook procedures can either be global (which means that they run on every application) or thread (only runs within your application). The document states that:
Global hooks are not supported in the .NET Framework
Except for the
WH_KEYBOARD_LL low-level hook and the
WH_MOUSE_LL low-level hook, you cannot
implement global hooks in the
Microsoft .NET Framework. To install a
global hook, a hook must have a native
DLL export to inject itself in another
process that requires a valid,
consistent function to call into. This
behavior requires a DLL export. The
.NET Framework does not support DLL
exports. Managed code has no concept
of a consistent value for a function
pointer because these function
pointers are proxies that are built
dynamically.
Which means, again, to monitor things that go on outside your application's view, you need to set a global hook, which can't be written in .NET.
I have exactly the same issue as this, and I think I have a workable solution. Initially I looked into a similar option to the one mentioned by 'tylerl'. In my case however, instead of using 'SetWindowsHookEx', I attempted to use the similar function 'RegisterShellHookWindows'.
Unfortunately, this only succeeded in providing me with notifications of when a subset of windows are created/destroyed. The only windows which it provided notifications for are those shown on the taskbar.
Since I didn't fancy hacking into other processes, or writing the native code which would be required for SetWindowHookEx, I tried digging into the .NET automation APIs introduced in .NET 4.0, and I think this has the answer to your problem (at least as far as detecting when windows are opened / closed).
Here's a code snippet for using this API to detect windows being opened/closed:
using System.Windows.Automation;
private void StartMonitoringForWindowEvents()
{
Task.Factory.StartNew(() =>
{
AutomationEventHandler windowOpenedHandler = new AutomationEventHandler(OnWindowOpened);
System.Windows.Automation.Automation.AddAutomationEventHandler(
WindowPattern.WindowOpenedEvent, AutomationElement.RootElement,
TreeScope.Descendants, windowOpenedHandler);
});
}
private void OnWindowOpened(object source, AutomationEventArgs eventArgs)
{
try
{
AutomationElement sourceElement = (AutomationElement)source;
string message = string.Format(
"Automation.WindowOpened PID: {0}, Handle: {1}, Name:{2}",
sourceElement.Current.ProcessId,
sourceElement.Current.NativeWindowHandle,
sourceElement.Current.Name);
Debug.WriteLine(message);
// for each created window, register to watch for it being closed
RegisterForClosedWindowEvent(sourceElement);
}
catch
{
}
}
private void RegisterForClosedWindowEvent(AutomationElement element)
{
try
{
string elementName = element.Current.Name;
int processId = element.Current.ProcessId;
int nativeHandle = element.Current.NativeWindowHandle;
AutomationEventHandler windowClosedHandler = new AutomationEventHandler(
(ignoreSource, ignoreArgs) => OnWindowClosed(nativeHandle, processId, elementName));
System.Windows.Automation.Automation.AddAutomationEventHandler(
WindowPattern.WindowClosedEvent, element,
TreeScope.Element, windowClosedHandler);
}
catch
{
}
}
private void OnWindowClosed(int nativeHandle, int processId, string elementName)
{
string message = string.Format(
"Automation.WindowClosed PID: {0}, Handle: {1}, Name:{2}",
processId,
nativeHandle,
elementName);
Debug.WriteLine(message);
}
You will need to add a reference to the assemblies 'UIAutomationClient' and 'UIAutomationClientTypes'.
Here's a link to the MSDN documentation (you'll probably particularly want to take a look at the information on events):
http://msdn.microsoft.com/en-us/library/ms747327.aspx
Important implementation Notes:
1.) Notice that in the sample, I used a task factory to register for reception of the automation events. It's particularly important to avoid using the UI thread when registering for automation events or generally interacting with the automation APIs. Doing so can (and usually quickly does) result in a deadlock. Therefore, I use the task factory to ensure registration is done via the thread pool.
This also means, that the events will be received on the thread pool... So, if you need to perform any UI updates, you will have to marshal these across to the UI thread.
2.) You'll also note, that I capture any needed information on the element which may be closed, at the time of registration (using a closure). This is because, once the element is closed, we will no longer have access to this information - since the element has been destroyed.
Phil
The answer is not C# (or .Net) specific. You'll need to call SetWindowsHookEx( WH_CBT, ... ). This will allows to know when a window is created, destroyed, moved, sized, etc. You'll also need to get the relevant information from the window to identify if its one you need to do something about. Perhaps GetClassInfo, GetWindowLong, and GetWindowText.
The problem with the SetWindowsHookEx is that in order to get events from every window you need to have a separate win32 dll with the function in question exported. Although you might have success with the procedure outlined here.
To expand upon Joel Lucsy's answer, you need to use the Win32 API. However, there's a nice library, the Managed Windows API, that provides an object-oriented wrapper over common APIs. It may have what you need.

Resources