Although I searched a lot, it is still unclear to me as to what exactly a "hook" is. For instance, I read this post on wiki answers :
A hook is a method of interposing a piece of code in front of another piece of code, so that the first piece of code executes before the second piece of code, giving the first piece of code an opportunity to monitor and/or filter the behavior of the second piece of code. An example might be a mouse hook, allowing the hook code to monitor the mouse while at the same time preserving the functionality of the original mouse event processing routine.
I also read this post, but I still don't understand what a "hook" exactly is. Can someone please explain, in layman terms, what is a "hook"? Why exactly do some write a "hook"? Also, is it possible to write a "hook" in Java?
Note:
I wanted to write a keylogger in java and one of my friend said that you will have to write a "hook" in C. Can't I write the whole keylogger in Java (to be operated on windows only)?
EDIT
please give an answer w.r.t keylogger. How can i ask kernel
to give the information about the key pressed to my application using hooking ? Or how can i register my application with OS using JNI? I want my application to record keys pressed by the user.
From Hooking - Wikipedia,
In computer programming, the term hooking covers a range of techniques used to alter or augment the behavior of an operating system, of applications, or of other software components by intercepting function calls or messages or events passed between software components. Code that handles such intercepted function calls, events or messages is called a "hook".
A good example built into Java would be Runtime.addShutdownHook
. A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently.
Runtime.addShutdownHook(new Thread(){
@Override
public void run(){
// do something before application terminates
}
});