Win7/8 DWM Draw hooking - hook

I am trying to develop certain extension for Desktop Window Manager. I selected method of DLL injection and function hooking. It is supposed to be working in Windows 7 and Windows 8.
I successfuly injected my DLL into dwm.exe process and hooked Direct3D device creation (D3D10CreateDevice1 on Win7 and D3D11CreateDevice/D3D11Device::GetImmediateContext on Win8). However, I have problem with hooking drawing procedures (Draw/DrawIndexed/etc.).
Whenever I replace pointers in vtable with pointers to my functions, they are restored back to original pointers in a while. Probably there is some hook protection in DWM/Direct3D??? I tried creating background thread which replaces the pointers still around. It works on Win7 but rarely on Win8 (it seems that pointers are restored more quickly there)
void thread(void* _device)
{
ID3D10Device1* device = (ID3D10Device1*)_device;
while(threadRunning)
{
if(device->lpVtbl->Draw != My_ID3D10Device1_Draw)
{
DX_METHOD_HOOK(device, ID3D10Device1, Draw);
DX_METHOD_HOOK(device, ID3D10Device1, DrawIndexed);
}
}
}
Does anyone have any experience with hooking and could he provide me some help? Thank you very much!

Related

Low level Keyboard Hook works on one on Windows 7 x64 and not another

I have a problem when trying to hook the keyboard (not a keylogger!) I´m trying to automate Word, then i´m calling dll with a especific hook.
I have a desktop and a notebook (the two have same antivirus + windows 7 x64), the only diference is that in the notebook the windows was installed with a newer version. THE PROBLEM: In the notebook EVERYTHING WORKS FINE. But in the desktop odd things happen: the hook was installed and works well if targeted to Notepad, but, when targeted to Word, though the hook was installed, the call to a external function is supressed!
LRESULT CALLBACK HookProc(int code, WPARAM wParam, LPARAM lParam)
{
if (code<0) {
return CallNextHookEx(HookHandle,code,wParam,lParam);
}
bool callNextHook = true;
if (callFunction != NULL) {
// ONLY WITH WORD AND ONLY IN THE DESKTOP callFunction SEENS TO BE NULL!!!
// this is a pointer to a function in main application
callFunction(code,wParam,lParam,&callNextHook);
} else {
ShowMessage("THE UNKNOW ERROR! THIS MESSAGE IS SHOWED, THEN HOOK IS INSTALLED");
}
//Call the next hook in the chain
if (callNextHook) {
return CallNextHookEx(HookHandle,code,wParam,lParam);
}
return 0;
}
I already tried disabling antivirus, changing user account control, running the program as admin... nothing works. What is causing this difference?
It probably has to do with the LowLevelHooksTimeout value in the registry.
On faster machines, they can process the hooks fast enough and make it under the default 200 ms to process timeout. On slower machines, they have a harder time.
For me I've had to bump up this value from the default to 500 ms (0x1F4) for my application involving hooks, to be reliable across machines.
To see the effect of changing this registry value, you have to restart your computer.
See the fourth paragraph in the remarks on the documentation here:
LowLevelKeyboardProc callback function
The hook procedure should process a message in less time than the data
entry specified in the LowLevelHooksTimeout value in the following
registry key:
HKEY_CURRENT_USER\Control Panel\Desktop
The value is in
milliseconds. If the hook procedure times out, the system passes the
message to the next hook. However, on Windows 7 and later, the hook is
silently removed without being called. There is no way for the
application to know whether the hook is removed.
Hope that helps.
Seems to be a bug in rad studio xe2, compiling the hook dll with xe6 resolved the issue. Interesting, with this bug and some extra code, was possible to hook both 32 and 64 programs with only one dll. This way, I continue using the old dll compiled with xe2.

Java Thread Safety v Displaying a Dialog from separate Thread

Hi noticed some code in our application when I first started Java programming. I had noticed it created a dialog from a separate thread, but never batted an eye lid as it 'seemed to work'. I then wrapped this method up through my code to display dialogs.
This is as follows:
public class DialogModalVisibleThread
extends Thread {
private JDialog jDialog;
public DialogModalVisibleThread(JDialog dialog, String dialogName) {
this.setName("Set " + dialogName + " Visable");
jDialog = dialog;
}
#Override
public void run() {
jDialog.setVisible(true);
jDialog.requestFocus();
}
}
Usage:
WarnUserDifferenceDialog dialog = new WarnUserDifferenceDialog( _tableDifferenceCache.size() );
DialogModalVisibleThread dmvt = new DialogModalVisibleThread( dialog, "Warn User About Report Diffs");
dmvt.start();
Now, as far as I am now aware, you should never create or modify swing components from a separate thread. All updates must be carried out on the Event Dispatch Thread. Surely this applies to the above code?
EDT on WikiPedia
However, the above code has worked.
But lately, there have been countless repaint issues. For example, click on a JButton which then calls DialogModalVisibleThread to display a dialog. It caused buttons alongside the clicked button not to redraw properly.
The repaint problem is more frequent on my machine and not the other developers machine. The other developer has a laptop with his desktop extended onto a 21" monitor - the monitor being his main display. He is running Windows 7 with Java version 1.6.0_27.
I am running on a laptop with Windows 7 and Java version 1.6.0_24. I have 2 additional monitors with my desktop extended onto both.
In the meantime I am going to upgrade to Java 1.6 update 27.
I wondered if the above code could cause repaint problems or are there any other people out there with related paint issues?
Are there any easy ways to diagnose these problems?
Thanks
So, you're breaking a rule, having problems, and wondering if these problems could be cause by the fact that you broke the rule. The answer is Yes. Respect the rules!
To detect the violations, you might be interested by the following page: http://weblogs.java.net/blog/2006/02/16/debugging-swing-final-summary
The easiest way to check if your problems are being caused by breaking the rules is to fix them (You should fix them anyway :-)
Just use SwingWorker.invokeLater() from the thread you want to update to UI from to easily adhere to Swing's contract. Something like this should do the trick:
#Override
public void run() {
SwingUtilities.invokeLater(new Runnable() {
jDialog.setVisible(true);
jDialog.requestFocus();
}
});
}
EDIT: You should make the 'jDialog' variable final for this to work.

Delphi - Thread not executing in ActiveX form - but does elsewhere

I have a thread, called TAlertThread. The thread interacts with its owner by triggering events. For example, when certain data is available inside the thread, it sets some temp variables and calls Synchronize(UpdateAlert) which in turn triggers the appropriate event.
Now the thread works perfectly in any standard windows application. My problem is when I put that thread inside of an ActiveX form (TActiveForm). The ActiveX control (aka COM object) is then embedded inside of a Windows Desktop Gadget (via HTML / Javascript). I also have experience with this, the gadget is not the issue. The ActiveX component works fine in its destination, except the thread is never executed. It's even being called EXACTLY the same way as I called it from the App.
Is this some limitation with ActiveX, blocking threads from executing? I wouldn't think so, because other things that require threads internally (such as TADOConnection) work. I am in fact properly calling CoInitialize and CoUninitialize appropriately. Again, works perfect in an application, but does not work at all in ActiveX.
Here is how I call this thread...
procedure TRMPDashXS.ExecThread;
begin
//Thread created suspended
lblStatus.Caption:= 'Executing Thread...';
fThread:= TAlertThread.Create(fConnStr); //fConnStr = connection string
fThread.Priority:= tpIdle;
fThread.OnConnect:= Self.ThreadConnected;
fThread.OnDisconnect:= Self.ThreadDisconnected;
fThread.OnBegin:= Self.ThreadStarted;
fThread.OnFinish:= Self.ThreadFinished;
fThread.OnAlert:= Self.ThreadAlert;
fThread.OnAmount:= Self.ThreadAmount;
fThread.Resume; //Execute the thread
end;
I suspect this might describe exactly what you're experiencing in your version of Delphi:
http://soft-haus.com/blog/2009/02/10/codegear-borland-activex-threading-synchronization-problems/
which references the same article you cited:
http://edn.embarcadero.com/article/32756
I'm not sure if that helps ... but I hope it does. At least a little :)
PS:
Is there any particular reason you have to use Com/ActiveX and/or TActiveForm?
According to this article here: http://edn.embarcadero.com/article/32756 web browsers don't allow threading via ActiveX. However that still doesn't explain why it doesn't work when I put it in a C# application.

C++ MultiThreading with visual studio express 2010 Forms Application

I am developing a Windows forms application which connects to a piece of hardware, acquires a lot of data (~1 GSample/sec), processes it, and spits it out to the screen upon a button click. I am now trying to automate the process in a loop that can be started/stopped at any time so I can monitor it whilst tweaking the input to the acquisition hardware. I thinks it's clear that I need to do this on a separate thread, but I'm having a heck of a time trying to do this in c++/cli - I have found a number of good examples using MFC, which is not supported by Express.
Specifically: My task is to press a button which is handled in Form1.h, to call a function in my main file Acquisition.cpp which contains the following code (currently an infinite loop)
void Form1::realTimeUpdate()
{
// live is a boolean variable set by a button on the form
while(live)
{
displayVariance(getVar(getQuadratures(100),nbrSamples));
}
}
I wish to execute this code in a separate thread so that the main program can listen for the user request to stop the operation. Without threading, I currently have to forcefully quit the program (or set it to run a fixed number of times) to stop it.
Is there any suggestions how I might go about running this code on a separate thread?
I've (unsuccessfully) tried a few things already:
Modifying the example given in This Microsoft Example. Problem: requires /clr:oldSyntax option which is incompatible with the other 1300 lines of code in the program.
Trying to do what I'd do in Java (Declare a global thread and start/stop it from any point in the code. Problem: Compiler won't let me declare a global System::Threading.Thread
this beautiful example. Problem: Requires MFC.
Any suggestions would be greatly appreciated!
You can use a BackgroundWorker or a Thread to handle this. You'll need to make sure that the portion of your work that updates the UI is marshaled back to the UI thread, however.
Here is a tutorial on threading in C++/CLI.
For the record, upon Reed's suggestion about using a BackgroundWorker, I sifted through the code at the bottom of this page and modified my code so that:
It created a new backgroundWorker BGWorker in which BGWorker->DoWork() called my realTimeUpdate() function.
A button on the main Form calls either RunWorkerAsync() or CancelAsync() depending on whether or not the process is running (checked by a boolean flag in my main program).
The realTimeUpdate() function is now passed a BackgroundWorker - realTimeUpdate(BackgroundWorker^ worker, DoWorkEventArgs ^ e) After each calculation is complete within the internal loop, it calls worker->ReportProgress(result) function. In the BGWorker->ProgressChanged() function a separate function, upDataUI(int) draws the result on the main form.
Thanks again for the help.

VC++ 6.0: Why is CASyncSocket::GetLastError() causing an access violation?

I'm using Visual C++ 6.0. I'm not sure of the service pack level of the visual studio installation, but the OS is Win 2K SP4. The failing code is part of a DLL.
Here's the code:
EIO::OpenConnection()
{
m_Client = new CSocket();
if(m_Client->Create() == 0) {
delete m_Client;
m_Client = NULL;
return CAsyncSocket::GetLastError();
}
if (!m_Client->Connect((LPCTSTR)m_IPAddress, 7)) {
delete m_Client;
m_Client = NULL;
return CAsyncSocket::GetLastError();
}
...<stuff>...
}
This compiles without error on my build system and executes without either of the calls to m_Client methods failing. When I move this DLL to the production system (Win 2K, not sure of service pack level yet), the call to m_Client->Connect() returns an error, so it goes into the IF block. CAsyncSocket::GetLastError() then the debugger to open and report an 0xC0000005 access violation. I don't understand this stuff enough to get anything out of the disassembly.
I've also tried CSocket::GetLastError() and m_Client->GetLastError() with the same results.
I'm fairly certain that m_Client->Connect() fails because of some security policy that's on the production machine that's absent on the development system, but I'd like to get the actual error code so I can help the IT guy narrow his search.
I haven't yet tried forcing a call to GetLastError() on my build system to see if I get an access violation there.
The GetLastError() method most likely calls WSAGetLastError().
But for WSAGetLastError() to work, WSACleanup() must not have been called yet.
I'm guessing that when you delete m_Client that exactly this happens.
Try calling GetLastError() before you delete the m_Client object.

Resources