Main page | About | Articles | Previous Posts | Archives

Thursday, April 27, 2006

Creating a global keyboard hook in C# without unmanaged code

Since every article about making a global hook with .NET had an unmanaged .dll making the hook, I'll just write here how to make one without any custom hooker DLLs.

Note: .NET cannot make a global hook for other events than WH_KEYBOARD_LL or WH_MOUSE_LL

With some small changes (KBDLLHookStruct to IntPtr), this code can be used for other hooks too.

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace WinHook {

public class KBHookEventArgs : EventArgs
public int HookCode;
public IntPtr wParam;
public KBDLLHookStruct lParam;

//Structure returned by a WH_KEYBOARD_LL hook
public struct KBDLLHookStruct
public int vkCode;
public int scanCode;
public int flags;
public int time;
public int dwExtraInfo;

//Hook Types
//more could be added
public enum HookType : int

Parts of this class stolen from MSDN and modified
public class GlobalKBHook {
//Callback for the hook
public delegate int KBHookProc(int code, IntPtr wParam, ref KBDLLHookStruct);

protected KBHookProc kbhook = null;
protected IntPtr hhook = IntPtr.Zero;

public delegate void KBHookEventHandler(object sender, KBHookEventArgs e);

public event KBHookEventHandler KBHookInvoked;

protected void OnKBHookInvoked(KBHookEventArgs e)
if(KBHookInvoked != null)
KBHookInvoked(this, e);

public GlobalKBHook()
kbhook = new KBHookProc(this.CoreKBHook);

public int CoreKBHook(int code, IntPtr wParam, ref KBDLLHookStruct lParam)
if (code < 0)
return CallNextHookEx(hhook, code, wParam, lParam);

KBHookEventArgs e = new KBHookEventArgs();
e.HookCode = code;
e.wParam = wParam;
e.lParam = lParam;

// Yield to the next hook in the chain
return CallNextHookEx(hhook, code, wParam, lParam);

public void Install()
int hInstance = LoadLibrary("User32");
hhook = SetWindowsHookEx(
(IntPtr)hInstance, //IntPtr.Zero for local hooks
0); //zero = global hook, otherwise use local thread ID

public void Uninstall()

//win32 api function for creating hooks
protected static extern IntPtr SetWindowsHookEx(HookType code,
HookProc func,
IntPtr hInstance,
int threadID);

//win32 api function for unhooking
protected static extern int UnhookWindowsHookEx(IntPtr hhook);

//win32 api function for continuing the hook chain
protected static extern int CallNextHookEx(IntPtr hhook,
int code,
IntPtr wParam,
KBDLLHookStruct lParam);

//Used to find HWND to user32.dll
public extern static int LoadLibrary(string lpLibFileName);

So uhh... that should be it... unless I forgot something. I have it a bit different in my app, so.. if you run into any probs with that and can't fix it.. just ask.

Basically to use that you'd do something like:

public partial class Form1 : Form
GlobalKBHook gkbh;

public Form1()
gkbh = new GlobalKBHook();
gkbh.KBHookInvoked += new GlobalKBHook.KBHookEventHandler(hookCallback);

private void hookCallback(object sender, KBHookEventArgs e)
//do something with the args here
//To get the key that was pressed,
//Keys key = (Keys)Enum.Parse(typeof(Keys),e.lParam.vkCode.ToString());

//if the key was pressed down, e.lParam.flags is 0, if the key was lifted, 128

Onwards, my loyal horde of wannabe-scriptkiddies who will presumably use this code to create their very own keyloggers!

and as a side note, I will probably post more frequently again after this small slow down... I'm again working on some intresting things.

Wednesday, April 26, 2006

Thinking about reinventing the wheel (withoug knowing about it)

A meaningful (?) post for a chance.

So, I am working on a bunch of classes which could handle some simple archives... file bit like .zips for example. So I think how should I implement this?

1. Maybe use XML... would work.
2. Maybe use file streams and make your own archive format (I've done this before with C++)
3. Use the one I made with C++

I scrapped the last idea since I'm quite sure that the library was quite bad :)

So I thought about making it with XML... That would be simple with the .NET built-in XML classes. The parsing of files from the package would be simple too.

but guess what?

The good folks at Microsoft had already done this! The classes at System.Resources starting with ResX.

Just give the ResXResourceWriter class a filename and call AddResource to add your file data into the file.
It takes a byte array, which can be easily obtained with System.IO.File.ReadAllBytes. Just pass your soon-to-be-packaged file as a parameter.

Extracting files from a ResX file is very simple too. Just use ResXResourceReader (or ResXResourceSet) and use it's GetEnumerator() with a IDictionaryEnumerator. The key will contain the resource's name and value shouod contain the byte array containing the data.

MSDN article on iterators, recommended reading about implementing IEnumerable into your own classes.
MSDN - System.Resources Namespace

Note that there's also another way to save resources in that namespace... Resource* classes, they save the stuff into a more obscure format if you like that more. I have no idea which one is better in terms of performance though.

The reader and writer both can do IO.Streams too. That means you, for example, do something like decompress the package file before extracting the resources and compress it again after saving.

So basically both my options one and two would've just been "reinventing the wheel". Oh well, I actually like doing that ;)

Wednesday, April 19, 2006

A boring news day

Nothing has been happening lately. At least nothing worth of writing. No good links, no nothing.

So I'll just post some randomness I ran into today...

Mega Man Effect
"The Mega Man Effect is an application that emulates an effect seen in the classic NES game Mega Man 2. When you launch an OS X Windows application, the screen goes dark, stars sweep the night sky and your application's icon is presented in a blue letter box bar with a cheesy 8-bit music introduction."

and for the musically curious people, samples from Super Eurobeat 167 can be found here.

Friday, April 14, 2006

Thoughts about IDEs, editors and related

As I convert websites into HTML as my job, do server-side programming in PHP and client-side programming in JavaScript etc., I've used many programs to ease the process.

At first I used notepad. I think most people start with notepad, and even some more experienced people use it. In my opinion, a basic editor like notepad is good for quick and dirty work, but it's nowhere near proper IDE's in terms of efficiency. Using a proper IDE also makes for better code, as the editor itself can, for example, auto-complete the ending tags in HTML.

After the notepad-phase I started using Ultra-Edit. Ultra-Edit is in my opinion the best text editor around for any kind of programming. It has lots of useful features, a hex editor, built-in FTP support etc. but it still lacks the features in editors made for more specific tasks like Dreamweaver, Visual Studio or Zend Studio. I still have it somewhere, although I very rarely use it anymore.

Adobe (former Macromedia) Dreamweaver is the industry standard in webdesign. It's also my weapon of choice for developing webpages.
For those of you who still think a WYSIWYG editor creates cluttered and horrible code ála Frontpage, welcome to 2006: Dreamweaver's WYSIWYG features create state-of-the-art HTML and CSS based layouts which validate with W3C's HTML and CSS validators.

The code editor in Dreamweaver is probably the best for coding webpages. It has autocompletion and pop-up lists for HTML, HTML tag attributes and CSS attributes etc. You can check the codes validity on the fly from the editor, check for possible compatibility errors in different browsers (eg. Netscape 3, Netscape 4, IE 6 etc.)...
The built-in CSS editor is also a great aid in quickly creating CSS styles. Although it might not always write the most compact CSS possible, you can easily check and fix this yourself.

Even though Dreamweaver is full of these advanced features, I still like to write code by hand. I use the WYSIWYG view too, though. I use it to see how does the site look. It's also very handy for laying out complex tables if you need to arrange tabular data.

The site-features are also excellent. I can create a site on my own computer and have the editor automatically update the files on a remote server. This is especially useful if I'm writing PHP in Dreamweaver, as I like to keep backups on my own hard disk too.
I probably don't need to mention this, but Dreamweaver can also work on remote files without making copies on the local machine.

There's also a HTML reference, a CSS referece, a JavaScript reference... all searchable, right in the editor.

Zend Studio is my primary tool for developing PHP applications. There's one feature here, what you won't find in any other program: local and remote debugging for PHP. No more stupid if($foo == "bar") { do something } debugging code. You can see the state of the variables right from the debugger, add breakpoints to stop execution at certain parts, run one line at a time and all the other features found in debuggers like the one in Visual Studio.

Other things worth mentioning is code profiling and checking. The IDE can check for typical problems, security holes etc. in your code. Has also some kind of support for HTML tag auto completion and such but I haven't really looked into that. Like I said, Dreamweaver for HTML, Zend for PHP :)

Now.. something I'd so dearly want...
an editor/IDE which combines ALL the best features from Dreamweaver, Zend and Visual Studio. The excellent HTML/CSS and overall features from Dreamweaver. PHP debugging and completion from Zend Studio, the simply excellent code-editor from Visual Studio. And throw in a JavaScript debugger.

Oh well. That won't probably ever happen unless Zend, Adobe and Microsoft fusion... which might not be a good thing. Microsoft Vistaloper Studio for web-design 2xxx Enterprise Edition? Guh..

Obviously, as I don't know everything, I don't either have an idea if there are better alternatives out there... so... link me if your opinion differs.


Thursday, April 13, 2006

Intresting coincidences....

...or I am able to affect the future!

You may have read about the capture of Bernardo Provenzano, a mafia-boss who had been hunted for years and years.

Well, just recently I had "aqquired" a song by an artist called "Molinaro & Provenzano". I like the song a lot and told a friend that it's great and stuff.
Just a day or two after, the italian police captured Bernardo Provenzano

An intresting coincidence I think.

I've had lots of similar intresting coincidences lately. For example, I've talked about a movie with a friend and bang, they happen to show it on TV a day or two after.
One time I talked about a finnish movie called "Bad Boys"... a day or so after, they show "Bad Boys 2" (the american film) on TV.

Coincidences or am I able to affect the future subconsciously? WHO KNOWS!

Tuesday, April 11, 2006

Windows Live Mail beta

And another Windows Live beta account for me..
This time, the new version of Hotmail: Windows Live Mail

Windows Live Mail is an advanced web based email. It's got all the features you'd expect from a normal webmail plus a bunch of nice advanced features.

The advanced features currently work only with Internet Explorer 6 or higher, but you get a new fancy looking "old-school" webmail for browsers like Opera. The interface is quite streamlined again, it's good looking but not intrusive. Simplistic, I might say.

The new interface in IE 6
The new interface in Opera 8

The new functionality is something you could find in a Windows email client, like Outlook. Windows Live Mail is actually quite similar to Microsoft Outlook 2003.

You have your mail folders on the left, mails in the middle and the currently opened mail on the right. You can also just drag and drop mails to other folders, just like you'd drag and drop files in Windows Explorer. Selecting multiple messages also works in a similar fashion as selecting multiple files in explorer (shift+click)

Everything works pretty quickly, as the page is done using AJAX techniques, so the browser won't need to reload the page for example if you click on another mail.

Quite nice work, just needs support for other browsers than IE.

Monday, April 10, 2006

Comparing classes and structs = pain in the ass?

I had a huge problem trying to figure out what was wrong with dictionary.ContainsKey() and dictionary[key].Contains().

The functions weren't working at all, might I say. I had a custom key struct and a list of classes as the value in the dictionary.

The functions would never return true, even if I had just added the elements to the dictionary. Why? whywhywhywhy?

After a bit of searching from google groups, I came upon a post about something not even related which had stuff about overriding GetHashCode() and Equals().

I was thinking... "Does my struct/class actually have a way to compare itself?"
Nope. C# is clever, but not clever enough to create a GetHashCode() and Equals() function for your classes.

Here's a simple example on how to make your classes and structs easily comparable:

class Example
string a;
string b;

/* put constructor and stuff here */

public override int GetHashCode()
return a.GetHashCode() + b.GetHashCode();

public override bool Equals(object obj)
if(obj.GetHashCode() == this.GetHashCode())
return true;

return false;

So... basically you just make GetHashCode() take some hash values, for example from the variables in the class and return the sum. Built-in types have a working GetHashCode() defined.
Equals() just needs to compare the hashes and.. well, that's about it. I think this is a simple and effective way.

Powering my code tonight:
Radio Stad Den Haag

Both great internet radios.

Saturday, April 08, 2006

Artificial Stupidity

Today I was lurking around Dan's blog like usual. He's got intresting posts about game programming and related stuff and best of all, it's C# baby.

After reading his post "Your very own Sky Net", which was about a simple AI, I wanted to do my own AI too. I'll probably do something simple. My idea at the moment was to do a small "life" simulator thing...

There would be a, let's say, "mouse". It would actually move on the screen too. You could drop things to the screen, like cheese and mouse traps or rat poison.

It would try to go eat the stuff you put there because it's a stupid mouse which lives only for eating. If it would eat rat poison, it'd lose HP or die. This mouse would be a respawning one though, and if it died or lost HP, it would understand that the thing it just ate isn't good for it.

Well, basically something like that. I'll see if I ever get to actually coding that. Maybe I will... it seems like a fun project.

C# Game Development: Your very own Sky Net

Thursday, April 06, 2006

Tools for tablets

I've been experimenting with various graphics/drawing tools recently, to find out which is the best program for doing my random sketching etc. with the tablet.

So far I've used Paint, Photoshop CS 2, Painter IX and Sketchbook Pro.

Paint is great for quick things. It's just so simple and if you don't mind rough lines, it's kinda fun too.

Photoshop is a good all-around tool. Although for some reason I don't really like to just plain draw stuff in it, especially when I could use Painter.

Painter.. now that's something different. I believe it's purprose-made for tablets. It's great for drawing things and painting. The brushes, pens and everything work really well and quite realistically too. Definitely worth trying out. There's a trial-version available at http://apps.corel.com/painterix/home/index.html

Here's something I've made in Painter. It's incomplete and I suck.. so..

I've just recently downloaded the trial of Sketchbook Pro so I haven't had lots of time to experiment with it... but it seems quite good. The interface is "optimized" for tables (or something) and it's easy to use. It does seem to lack advanced features like in Photoshop and brush/pen "simulation" like in Painter, but for the purprose of sketching and just drawing things, it seems quite good. You can get a trial of Sketchbook Pro from http://usa.autodesk.com/adsk/servlet/index?id=6848332&siteID=123112

I drew HG in Sketchbook Pro

There's also a program by Xara which is quite good for vector-based drawing. I used it earlier to draw with the mouse... but I can't quite grasp the name. It was probably one of the easiest and the most intuitive vector drawing programs though.

That's all for now. No programming stuff... darn.
And here's something fun (weird?).

Wednesday, April 05, 2006

Mind boggling

A friend linked me to this game yesterday. It gave me a damn headache!
Basically the idea is simple. You just connect the same colored blocks to each other... but it gets increasingly difficult. I've got through all the levels (30 in total). Beware, 16 and 23 = difficult as hell.

and as a side note, I updated my time tracker application a bit. It now has a "fancy" tray icon which when clicked pauses or continue the current task (if one is being ran at the moment). I used QTAM Bitmap to ico to create the icons from a bmp made in Paint.

And obviously the prog itself hides to the tray when minimized.

I will probably update my project page on zTimeTracker to allow downloading later today.

You did notice the project links on the right, didn't you?

There's nothing more to see here. Move it move it move iiiit.

and I started using target="_blank" in the links in posts. yay

Tuesday, April 04, 2006

State of the time

The functionality of my time tracking application is stating to shape up.

At the moment, you can...

  • Fill in task details and track time spent

  • Compile a list of tasks and their details (automatic)

  • Save and load task lists

  • Generate a report of the tasks

It's looking good. Very good actually.
I will probably work out some bugs in the time saving and add a tray icon and some functionality to it and release some kind of a test version for the curious to look at.

The saving and loading was easy to implement, thanks to .NET's good use of XML. The tasks are saved into a DataSet inside the app, so I just pop out the XML from the DataSet with WriteXml() to save and use ReadXml() to open. Easy!

Another very nifty feature about XML is XSLT. You can use XSLT to transform XML documents into other documents. And as .NET supports XSLT... there couldn't be an easier way to transform the data from the DataSet into HTML other than using XSLT to transform the XML data.

I've worked with XSLT quite much at my current internship job. I've done various XML to HTML translations and one which converts XML into plain text.

If you don't know what XML or XSLT are, here's some links to get you started:
W3Schools XML tutorials
W3Schools XSLT tutorials

W3C XML page

If you're using .NET, check MSDN's articles about System.Xml namespace.

Monday, April 03, 2006

Game programming - the fast and fun way?

What's the fastest way to program a game? Use HTML and JavaScript!

I've made plenty of experimental games with the two. Tetris, helidrop, etc.
The latest experiment I'm working on is a side-scrolling shooting game.

Why do I use HTML+JS to write games? Because it's simple! You have the graphical side and pretty much everything you need for a simple game already laid out.

The basic principle behind most of my HTML+JS games is the following:
every object is a div-element with an "position: absolute" CSS-attribute. That way I can easily put it anywhere on the screen.

Because of HTML, I can easily add graphics or colors or whatever. Just set the div's background color or background image to something.

All you need to do to get a simple game loop is the following:
Set up event handlers for keyup and keydown to get keyboard input

document.body.onkeyup = keyUp;
document.body.onkeydown = keyDown;

Set up a game-loop "ticker"
function tick()
insert some function
calls here, like
doLogic() or something

To start the game all you have to do is call tick()
I usually have a init() function which is called in body tags onload event.
It creates the initial objects in the game, initializes variables etc.

For example, if we wanted to insert a red box in the "game field" in init()...
var box = document.createElement('div');
box.style.position = 'absolute';
box.style.left = '200px';
box.style.top = '200px';
box.style.backgroundColor = 'red';
box.style.width = '50px';
box.style.height = '50px';
box.id = 'player';


With the box.id given, you can easily get the object anytime you want by calling document.getElementById()
Another way would be to save the object to a global variable, which is something I don't really like.
I dunno which one is better performance-wise... so I'm just applying basic programming ideals: globals = bad

Now if we wanted to move the box down a bit, we could just make keyDown() check if down arrow is pressed and increase the box.style.left value. Note that there's the little part "px" after the value, so you need to make sure you don't try to add directly into the value or you'll end up with something like "200px1"

I usually make a helper function to get a value without the px ending.

Maybe I'll write more about this subject later on.

Some old version of a JavaScript Tetris I've made can be found here

Fading imagery

Last night while trying to fall asleep, an idea just popped into my head: A image fader made with JavaScript...


Image fader

Tested to work with IE, Safari,Opera 9 and Firefox. Yes, the images are blatantly stolen from around the web. Shoot me.

and wtf? Opera 8 doesn't support opacity? Damn... Well, at least it rotates the images...

The idea behind the script is relatively simple, but there was a small problem with IE implementation...

Basically what you do is make a structure like <div><img></div>, where the div will contain the image to fade to and the img will contain the image in fading.
Fading is done by reducing the CSS opacity value or filter: alpha(opacity=something) value in IE

Feel free to study the code or use it for something if you find it useful... a comment or link back here would be nice if you do tho.

With a little work, one could easily convert that into a banner rotator with changing links when images change.

Time tracking

As I recently posted, I've been looking for a way to easily keep track of how much time I spend on certain tasks I do, like coding a webpage for a client etc.

Well, I didn't find any small and useful app to do it for me, so...

Basically it just has those fields which you fill and a clock. You can pause the clock if you stop for a while or such, and stop it and the task you've been working on will be added to the list.

I'll be adding some features like loading and saving task lists, generating billing info etc.

Sunday, April 02, 2006


I've recently been killing my boredom by browsing the galleries at Superdickery.com, which is a site about stupid comic book covers.

Mostly about Superman comics and it's spinoffs, it's a really good laugh. Definitely worth of checking out. I especially like the WW-II era propaganda themed covers.