What does AFX_MANAGE_STATE(AfxGetStaticModuleState()) do exactly - c++

I have used a lot of modal dialogs and they worked fine without the use of AFX_MANAGE_STATE, but recently I was working on a different project in which the resource dlls are different from the launching dll. I surfed the web and found out the above line and when I inserted it before launching the dialog, it worked. I guess that maybe since we have different dlls, we need to load the state of the main dll in order to launch the dialog, but I am not sure. I have not been able to find a good explanation anywhere on the internet. Could anyone please explain in simple terms what AFX_MANAGE_STATE does and why I suddenly had to use it.
Thanks.

Every .exe and .dll has an internal resource handle, pointing to your dialogs and other resources. If you call a function in your DLL, the current resource handle is pointing to the resources in the .exe, which is wrong and needs to be changed to the resources of the DLL.
This is what AFX_MANAGE_STATE does.

AFX_MANAGE_STATE is a macro which calls resource function so that resource would be looked up only in this DLL, and not the EXE/DLL from which particular function is called. This macro also causes AFX_MAINTAIN_STATE class to be put on stack. This class would, on exit of function, reset the resource lookup, so that EXE/DLL that called this exported function gets it resource searching back.
In C++ terms:
// Some exported function that launches GUI or uses other resources
int GetSomething()
{
AFX_MANAGE_STATE();
...
}
Would be something like (not exactly):
int GetSomething()
{
SetResourceSearchingToThisDLL();
AFX_MAINTAIN_STATE state_RAII;
//Use resource
// Compiler will put destroctor call for state_RAII object here
// which will mean AFX_MAINTAIN_STATE::~AFX_MAINTAIN_STATE()
// And that would call something like:
ResetResourceSearching();
}
Usage of this macro, within same DLL call stack wont hurt anyone, since Resource-Searching has some usage-counter, which will revert to caller (DLL/EXE resource) only if it reaches 0.
It is important to note that, not every MFC DLL has to use this macro. It is only if DLL is loaded by non-MFC client, may be by a C client, a C++ console based application, .NET client etc (yes, may be MFC Windows application client also).
If your EXE and DLL are made in MFC, using same MFC/Compiler/linker version and has one CWinApp object, you need not to use this macro.

Related

How would I go about invoking the ui from within a DLL?

This may be too broad a question, but I have a DLL that contains a UI. It is currently invoked by an EXE. What steps would I do to try and invoke the UI within the DLL? Or put another way, how would I go about teasing out the code that would invoke the UI as it happens in the EXE?
Looks like you have access to source for both dll and executable that uses it. so what you are doing is writing a host for that dll from scratch.
Create a MFC application from VS project templates (make it the same kind as main executable, dialog, single document, multiple document, etc).
Look at what function dll exports, also look at its headers and best of all -- documentation.
Search source code of main exe and find the places the dll functions are called.
Figure out what is being done and why.
Narrow down scenarios you want to reproduce (initialize dll, show basic UI and tear down)
Start reproducing that code in your example app.
Copy the dll call, see what parameters it takes, see how those are initialized, etc.
Fix errors as they come up.

Convert Win32 Application to Object

I'm pretty new to WinAPI programming, and have written a Win32 application for screen capture. When I run the program, the cursor immediately changes to a crosshair and I can click and drag to capture a portion of the screen and save it to file.
However, I'd now like to modify my program so that it doesn't contain a main method (WinMain) and essentially turn it into an object class rather than an application class so I can call functions from other programs. I haven't been able to find a good resource on how to do this, as I believe WinMain carries out special functionality under the hood so I can't simply change the name of the method.
Can anyone suggest some good resources or tutorials that address this?
There are many ways to do that, but you have fist move one step back:
How do yopu expect your "program" (let us continue to call that way) to be called?
With which parameters and what return type?
Then, what kind of API do you want to expose? A C++ class in header? a C++ class from a static library?
A C function exported from a DLL? an COM object?
There are many sample on how a library or a DLL or a COM library looks like (just try google those keywords).
The simple way is most likely to set up a library or a DLL project (most IDE have wizard that provide empty skeletons), than paste in it the relevant code that you require to leave there, letting it be called from the exposed function or class method.
A more precise answer can be given only after you decided which "form" your "object" should have.

Control Win32 process from injected DLL (VC++.NET 2010)

I've injected a DLL file into another process and I wish to communicate with it though an external EXE. How can I communicate with the injected DLL? :/
If I've understood your question properly, you have injected a DLL to a process and want to communicate with it via some external EXE. You can use the standard methods of IPC (Interprocess Communication) here. I know a link should not be posted by itself but IPC on Windows is too broad a topic to cover comprehensively without copy and pasting from the linked article.
I have done the same thing as what you are attempting here and used named piping and data copying via WM_COPYDATA for IPC. However, there was a particular reason why I used each form of IPC so we really need to understand more from your problem domain before recommending a single one.
Something unrelated that you are doing is that you are calling CreateThread on a function you have casted to LPTHREAD_START_ROUTINE, which means it should point to a ThreadProc callback. Your current signature of void WINAPI () does not match the required DWORD WINAPI (LPVOID).
If all your DLL needs to do is to forward messages, it is possible to have it act as a proxy for messages.
Have the DLL create an invisible window
Pass the window handle to the source process
Have the source process dispatch messages to this window
The DLL will receive these messages and can then forward them to the destination window
However, if this is all you need to do then there is no need to have a DLL in the middle at all. This is why I say we need more information about your problem domain.
If you are trying to have something in the form of an executable which injects a DLL, then communicates with the DLL and the DLL communicates back, you might want to take a look at a project I worked on a while back. This does exactly that.
You need to communicate between your EXE and the application your DLL has been injected into.
So in your DLL you will need to spawn a thread that waits for some kind of communication from the EXE. You cannot wait for the event in the DllMain, because that will deadlock the application.
A simple way to do it is to create a named event and wait for it to be set in your DLL. Then in your external EXE, when your button is clicked, you set the event.

COM & CoGetClassObject()

I have a little problem with CoGetClassObject().
I have an application which must use some DLLs of a specific version,
but they are also present in the system, in a more recent version.
So I start hooking the CoCreateInstance() and loadLibrary(), which I guess are good.
The problem is that the DLLs in the two versions are loaded.
So I think that CoGetClassObject() is the problem/solution because it provides a pointer to an interface of an object associated with a CLSID containing a DLL that the application must use in an older version.
But I don't know what this function "does", so how can I "override" this function ?
thanks.
PS : I'm new in the COM programming.
CoGetClassObject() simply does half the job that CoCreateInstance() does. It returns a class factory. CoCreateInstance() then call IClassFactory::CreateInstance() and releases the IClassFactory. You would only use it if you have a need to create many objects of a certain coclass and want to optimize that. It avoids the cost of creating and releasing the factory over and over again.
You are possibly overlooking a far simpler solution to this problem. You can simply copy the new version of the COM server DLL into the same directory as the client EXE. And create a zero byte file with the name "app.exe.local" where "app" is the name of the EXE. That's enough to force that copied DLL to be loaded instead of the one that the registry points to. The MSDN Library article about DLL redirection is here.
The very simple explanation is CoGetClassObject() opens HKCR\CLSID\{ClassId} and looks at InProcServer32 or LocalServer32 depending on what CLSCTX_* value is passed - that is the COM server path.
Once it find a COM server file path is loads (LoadLibraryEx() with LOAD_WITH_ALTERED_SEARCH_PATH flag in case of in-proc or CreateProcess() in case of out-proc) the COM server. Then it locates and calls DllGetClassObject() for in-proc servers or waits until a class factory is registered for out-proc servers.
This of course ignores stuff like DCOM etc. You can get a better idea of how it traverses the registry using Process Monitor utility.
If you want to load a specific COM DLL regardless of whether there is a newer version installed, and regardless of where the older DLL is located, then simply ignore CoCreateInstance() and CoGetClassObject() altogether. Load the older DLL yourself via LoadLibrary(), then call its exported DllGetClassObject() function directly to get the DLL's IClassFactory interface, then call IClassFactory::CreateInstance() as needed. This is all CoCreateInstance() and CoGetClassObject() do internally anyway, but this bypasses the Registry lookups they perform to determine the DLL path to load.

C++ hook process and show status

Ok so I am learning C++ slowly. I am familiar with all the console syntax and everything, but now I'm moving on to windows programming. Now what im trying to do, is create a DLL that I inject into a process, so it's hooked in. All I want the C++ application to do, is have text in it, that says "Hooked" if it's successfully injected, and an error if something wrong happened. Or even if I can do it without a DLL, Just open an executable, and when the certain process I'm trying to hook is opened, the status is changed to "Hooked". Also I have a safaribooksonline.com account so if there is any good reads you would recommend, just write it down. thanks
I think you might be looking at this backwards. In C/C++ an application 'pulls' a DLL in rather than having a DLL 'injected' into an application. Typically for plugins/hooks, there is some mechanism to inform an application of a DLL's availability (often just its presence in a specific directory) and a configuration file or some other logic is used to instruct the application to explicitly load the library, extract a function or two, and call them.
For Windows programming, I'd suggest doing a search for examples of the LoadLibrary() API call. You'll likely find a tutorial or two on how to do it.
If by "hooked" you mean, "have my DLL run in that processes' address space", you want CreateRemoteThread(). This is fairly advanced and difficult to debug, because your bugs make the other program crash. It's how a lot of malware works, by the way.
If you mean "have my DLL get notified of activity in the other process", you want SetWindowsHookEx().
Sounds like you want to inject as soon as the application starts? You can do that with Microsoft's Detours DetourCreateProcessWithDll(). Example here.