Delphi API Hooks behave oddly - api

I'm trying to implement an API Hooking mechanism.
What I have so far, is a DLL injected into other processes via a SetWindowsHookEx call, and some code to implement the hooks themselves.
For example, I can successfully hook MessageBoxA calls across multiple different applications (thats not the end goal).
What I need to do is hook some graphics functions, in particular textout functions as I need to be able to screen scrape.
Now - I'm aware which textout functions I need (TextOutA/W, ExtTextOutA/W for the application I'm trying to access), and I'm aware I need to hook Begin/EndPaint or Get/ReleaseDC to match the DC's to window handles and determine if the textout is on a window I'm interested in.
My problem is that while I can hook the textout functions, messageboxes and so on without any problems what so ever, GetDC results in a hard crash as does BeginPaint.
The code is quite long, so I'll post what I'm having problems with, but I can post more if it helps.
The rough frame work is as follows;
function CustomBeginPaint(hWnd: HWND; var lpPaint: TPaintStruct): HDC;
begin
UninstallHook();
Result := BeginPaint(hWnd, lpPaint );
InstallHook();
end;
Even this quite simple function fails constantly, returning zero.
I'm at a complete loss to explain whats going on, as the hWnd is always 1309192 despite trying this on multiple machines.

So the key issue was, as Andreas Hausladen mentioned thread safety - but not due to the VCL.

Related

What is the cleanest way to notify GUI to update in wxWidgets?

I have a small application that needs to update GUI elements if some event occurs in lower levels, say, socket goes off-line, or something like that.
In Windows, I could use PostMessage which would be sent through the chain to all Windows, and the required ones could update accordingly.
How can I achieve something similar in wxWidgets? I cannot use OnUpdateUI, or something like that, because some controls doesn't seem to handle that at all.
The target window could be one or multiple, they could be frames or controls, so I'm confused a little here.
Does anyone have a suggestion?
First, all controls do receive EVT_UPDATE_UI so you could use it for this and it's a very simple of doing it -- but also the most inefficient, so definitely not recommended for something like socket event processing (it's fine for checking whether the socket is connected or not though).
Second, the exact equivalent of Windows ::PostMessage() is wxQueueEvent() (which used to be called as wxPostEvent() actually but the new version is preferable). wxQueueEvent() is thread-safe in the sense that it can be used from a secondary thread to post an event to a GUI control managed by the main thread.
You can use the same approach as in Win32 apps. You can create the custom event class and send it to windows using wxPostEvent function. There are some docs regarding this.
Not sure what you mean about wxUpdateUIEvent - from my experience it works pretty fine. What controls do not receive it? Did you add EVT_UPDATE_UI() macro to event table?

Visual Basic program sometimes does not update screen anymore and does not respond to user input

I have a program written in VB 2010 express under windows xp which does some heavy number crunching combined with serial communication. When it "gets too busy" it does not update the screen anymore (done simply with Textbox.text = "any text") and it does not respond to user input in any text box. Not even to a click on any text box.
Is there a way I can get the program to do screen update and respond to user input while it is busy?
thanks
Use a BackgroundWorker to perform intensive work (rather than using the UI thread):
VB.NET BackgroundWorker Use
How To Update Controls Using BackgroundWorker in VB.NET
If you need finer grain control then create and manage your own threads: Multithreaded Applications (but the BackgroundWorker would probably meet your needs).
You'll probably need to move the heavy calculation and communication to a separate thread. In other words, it sounds like you may need to do some multithreading.
From the description of the problem, it sounds like the GUI updates and the calculation are performed in a single thread, therefore, when the heavy calculations are taking up all the computing resources, there's no computing resources to update (or respond to) the GUI.
An approach to take in these types of situation is to start a new thread with computation intensive (or potentially blocking operation such as I/O) processing in a separate thread, allowing the GUI to stay alive on the main thread.
Microsoft seems to have an introduction to multithreaded applications in Visual Basic, using the facilities provided in the .NET framework, so that might be a good starting point.
This question is tagged VBA and I will respond accordingly. If the tag is wrong then this answer can be disregarded.
Is there a way I can get the program to do screen update
The DoEvents statement will force a screen update.
Sometimes DoEvents is not enough. An alternative is proposed here.
Add the following line at the top of your module (outside of your function):
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Then add this line in place of, or in addition to, DoEvents:
Sleep 1 'This will pause execution of your program for 1 ms
You might try increasing the length of time you pause the program using sleep if 1 ms doesn't work.
and respond to user input while it is busy?
This is not possible in VBA.

Google map memory usage on VB.Net form

I am using a Google map inside of vb.net application. The problem is that it keeps taking a memory space whenever I search a map on a web browser which is on a windows form . Even though I close the form, it is not disappeared from memory. The size of memory is just going up. That goes away when I close MDI form.
What is the solution for this? How do I manage the memory problem?
-->Edited : One of out team member found the solution. It worked out pretty well. Just call the function whenever you want to do it. I used it on Form Closing event.
<DllImport("psapi.dll")> _
Public Function EmptyWorkingSet(ByVal hProcess As IntPtr) As Boolean
End Function
<DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _
Public Function GetCurrentProcess() As IntPtr
End Function
Public Sub FreeMemory()
EmptyWorkingSet(GetCurrentProcess())
End Sub
Check out my answer to this question. I believe your best bet is to do some profiling.
I ran the trial version of ANTS memory profiler, against an app I was working on and the problem I discovered is outlined in this walthrough of how to use the tool (specifically the details around figures 10 - 15).
Basically, I was subscribing to some events on a form, but then not unsubscribing from them when the form was closed. This meant there was still a reference to the form and it (along with all it's controls and members) were never collected.
Maybe you have a similar situation, but your best bet is to look at the code in a profiler. It doesn't have to be this one (this is just the one I've used). It will certainly help you identify the root cause of your problem.
This is from the liberal garbage collection in .NET. If you're really concerned about memory, try this.
First, ensure that the objects you wish to remove have been disposed. If this is a Windows Form, this should be automatic.
Call System.GC.Collect(). You should see your memory usage decrease.
As a work around you could use an MDI parent and put your maps into MDI child forms opening up a new one each time (or periodically closing unused ones)?

why we must place a global hook procedure in a separate DLL

i read some article and msdn and blog but have some question
why we must place a global hook procedure in a DLL separate from the application installing the hook procedure
and what is different from global hook and keyloger( i write key loge without separate dll)?
how key loger intercept all application keyboard message without separate dll?
finaly
what code is in dll for global hook ?
please give some step for writing global hook with detail
Basically there are two ways how to capture keystrokes globally (the keylogger can use any of them):
Using global keyboard hook.
This method needs a HookProcedure located in seperate DLL file as you stated above. This is the right way how to capture keystrokes, because your function is called only on each keypress.
This article could be useful: http://www.codeproject.com/KB/DLL/keyboardhook.aspx
Calling WinAPI function GetKeyboardState. This method doesn't require separate DLL file, but have a big drawback. The function returns only actual state of keyboard. It is necessary to call it in an infinite loop (probably in separate thread, but not necessarily) with a little sleep time to caputre all keystrokes.
This results in increased CPU usage. I don't recommend you to use this technique. Also an antivirus software with good heuristics will consider such code as keylogger.
A keylogger without DLL probably uses the second approach or generates the DLL on the fly.

Is there a way to force the VB6 IDE to unload libraries?

When debugging a VB6 application, I have noticed that the VB6 IDE keeps any libraries loaded if they were used by the application being debugged. The library remains loaded between debugging sessions. This interferes with my debugging because unfortunately, one of our libraries (written in delphi) keeps state around in global variables and has significant initialization/termination logic.
Simplified example of the problem: I have a foo.dll with a counter inside it. I access this counter with the following declares in VB6:
Public Declare Function GetCounter Lib "foo.dll" () As Long
Public Declare Function IncrementCounter Lib "foo.dll" () As Long
The problem in this case is that the counter is not reset when I start a new debugging session. I would rather not write application or library logic to take this "recycled library state" scenario into account. I want to be able to start a debugging session with a clean slate.
Currently I force a library unload by restarting the VB6 IDE. Is there a better way?
edit: I played around a bit with invoking kernel32.dll functions to unload/reload libaries from the immediate window; this turned out to only be a good way to crash the IDE or cause random behavior. I should have expected that as the IDE has no way of knowing that it's original handle for the library has become invalid.
I have accepted AngryHacker's answer as I am now convinced that restarting vb6.exe is the only way to start a VB6 debugging session with a completely clean slate.
I've struggled with that for years back in the day, particularly when coding ActiveX DLLs for use with IIS sites.
The only real antidote I found was to keep the library loaded in a separate VB6 instance (assuming you have the control of the source). That way you could simply press the Stop button on the toolbar and the library would no longer be loaded.
You should look at a few things:
Make sure you are disposing of any class references by setting your local or global variables = nothing when your application exits.
When debugging, NEVER hit the end/stop debugging button. This just pulls the rug out from under the code and can sometimes leave things hanging in memory.
Don't use the End command in your application exit code (see point #2).