473,626 Members | 3,216 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

local keyboard hook

Is it possible to do a local keyboard hook to a process running in a
new thread. The process is a command line application and is
instanciated when a button is pressed on the main form. I have had the
hook working Globally, but this means that the hook logs keystokes
from the main app as well as the keystrokes fom the CMD process. The
hook is WH_KEYBOARD. I have tryed passing the threadId into setkeyhook
and thence to SetWindowsHookE x but the KeyboardProc never gets called.
Has anybody got any ideas?

Apr 16 '07 #1
2 4421
"bizcor" <st***********@ metronet.co.ukw rote in message
news:11******** *************@y 80g2000hsf.goog legroups.com...
Is it possible to do a local keyboard hook to a process running in a
new thread. The process is a command line application and is
instanciated when a button is pressed on the main form. I have had the
hook working Globally, but this means that the hook logs keystokes
from the main app as well as the keystrokes fom the CMD process. The
hook is WH_KEYBOARD. I have tryed passing the threadId into setkeyhook
and thence to SetWindowsHookE x but the KeyboardProc never gets called.
Has anybody got any ideas?

Processes do not run in threads, cmd runs a separate process not related to the thread that
spawned this process.
What you need is the thread in the cmd process that owns the main window handle, you can get
this TID by a call (through PInvoke) to "User32" GetWindowThread ProcessId API .
Willy.

Apr 16 '07 #2
Thanks Willy

I have now tried this and cannot get it to work!
can you look at the code snppits below to see if I am doing it
correctly:

Many thanks Steve[bizcor]

Code from Main form....

private void button11_Click( object sender, System.EventArg s e)
{
try
{
ThreadStart mts = new ThreadStart(run Application);
Thread t = new Thread( mts );
t.Start();
}
catch(Exception ex)
{
Debug.WriteLine (ex.Message);
}

}

private static void runApplication( )
{
try
{
process1 = new Process();
process1.StartI nfo.FileName = @"c:\phylip\seq boot.exe";
process1.Enable RaisingEvents = true;
process1.Exited +=new EventHandler(pr ocess1_Exited);
logger.SetFileN ame(@"c:\logger .txt");

// This does not work
//uint threadid1 = GetCurrentThrea dId();
//Debug.Write("Cu rrent thread id 1 is: ");
//Debug.WriteLine (threadid1);
//uint threadid2 = (uint)AppDomain .GetCurrentThre adId();
//Debug.Write("Cu rrent thread id 2 is: ");
//Debug.WriteLine (threadid2);
//logger.StartLog ger(threadid1);

process1.Start( );

// Try Willys method
// Get processes window handle
IntPtr hdlWin = process1.MainWi ndowHandle;

// Set trHandle to null ?
IntPtr trdHandle = (IntPtr)0;

//Call method to get window thread
IntPtr retThread = GetWindowThread ProcessId(hdlWi n,trdHandle);

Debug.Write("Wi ndow Thread is: ");
Debug.WriteLine (retThread.ToIn t32());

//Call startlogger to set the hook
logger.StartLog ger((uint)retTh read.ToInt32()) ;
}
catch(Exception ex)
{
Debug.WriteLine (ex.Message);
}

Methods from Keylogger class ....
public bool StartLogger(uin t byThread)
{
if(!isstarted)
{
FileInfo finfo = new FileInfo(sbDefa ultFileName.ToS tring());
if(File.Exists( sbDefaultFileNa me.ToString()))
{
finfo.Delete();
}

using (StreamWriter swLog = finfo.CreateTex t())
{
swLog.Close();
}
finfo = null;
_ptrHookID = SetHook(_proc, byThread);
isstarted = true;
return true;
}
else
{
return false;
}
}

private static IntPtr SetHook(Keyboar dProc _proc, uint byThread)
{
//Set hook from the current process
//Use using to allow auto Dispose
using (Process curProcess = Process.GetCurr entProcess())
using (ProcessModule curModule = curProcess.Main Module)
if(byThread==0)
{
Debug.WriteLine (curModule.Modu leName.ToString ());
return SetWindowsHookE x(WH_KEYBOARD, _proc,
GetModuleHandle (curModule.Modu leName), 0);
}
else
{
Debug.WriteLine (curModule.Modu leName.ToString ());
return SetWindowsHookE x(WH_KEYBOARD, _proc,
GetModuleHandle (curModule.Modu leName), byThread
);
}
}
Apr 17 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
13017
by: daFritz | last post by:
Hi! I need to prevent Task-Switching in my App, so I tried to implement a low level keyboard hook in a extra class. But it seems that the Parameters are not passed correctly to my Hook function. Similar Examples in VB .NET work correctly. Heres the Source Code: using System; using System.Runtime.InteropServices;
2
5430
by: Christoph Brüser | last post by:
Hi, in my application I want to react to certain keys when a context menu is showing. So I installed a keyboard hook, but now whenever a key is pressed when the menu is showing, the application crashes and sometimes throws a NullReferenceException in system.windows.forms.dll. I assume that the hook somehow messes up the context menu's message loop or something like this. I also had this problem with a mouse hook, so i guess its a...
0
1391
by: BobAchgill | last post by:
When I try to hook a non letter key like left arrow (37) all is OK. If (Hookstruct.vkCode = 37) Or (Hookstruct.vkCode = 83) And CBool(Hookstruct.flags) Then But, for example, the hook for the letter "s" key (83) does not work. Mysteriously, the "s" starts hooking properly after I set and continue through a break point. I can even then remove the breakpoint and the "s" continues to hook OK as long as I have the debug session going.
7
26532
by: jpierson | last post by:
Hi, I am tryin to create a keyboard hook that sends the keystroke ctrl + pause/break. I haven't used keyboard hooks before so I'm not too sure how to use them public int MyKeyboardProc(int nCode, int wParam, int lParam) {
0
2608
by: Hema | last post by:
hi all, i have implemented a keyboard hook which is active only when IE is open. Its a BHO. I am adding the code below: using System; using System.Runtime.InteropServices; using System.Windows.Forms; using System.Web.Services; using Microsoft.Win32; using SHDocVw;
1
6814
by: Louis Cypher | last post by:
I'm working on an application (OEM) using c# that uses input from a keyboard and a USB Barcode Scanner. I need to be able to identify keystrokes from the barcode scanner and remove them from the message queue, regardless of what application has focus. I can identify the keystrokes and input device by registering for raw input (RegisterRawInputDevices) and processing the WM_INPUT message. This gives me the keystrokes and the ability to...
1
11213
by: Louis Cypher | last post by:
I'm working on an application (OEM) using c# that uses input from a keyboard and a USB Barcode Scanner. I need to be able to identify keystrokes from the barcode scanner and remove them from the message queue, regardless of what application has focus. I can identify the keystrokes and input device by registering for raw input (RegisterRawInputDevices) and processing the WM_INPUT message. This gives me the keystrokes and the ability to...
2
1431
by: Frank | last post by:
In a dialog box procedure is there a way to determine if keyboard input is from the keypad or the arrow keys? I need to know if the input is from the main keyboard keys. Thanks
2
5972
by: Justin | last post by:
So I have a keyboard hook that I have implemeted into my c# app. I need to not allow any hotkey actions to be performed when my app is opened. I can capture the key events and handle them if I want to. The only problem is that I have fields that require input. Do I have to programmatically add the characters to the input fields when I am handling the event. I don't want these keys sent to the system. But only to my program. Or does...
0
8268
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8202
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8707
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8641
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8510
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7199
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5575
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4202
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2628
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.