windows API using c#

sup y'all... how do yo find out the available functions, the parameters required for each, and the functionality provided when using c#?? i remember there used to be a tool in visual basic 6 but i dont have that installed anymo.

im looking for the name and parameters of a function that tells u when a  key is pressed and also what key it was so if u know of one or can find out plz tell me.

(the reason i want to use the windows api for this is so that even if the form loses focus, i will still know when a key is pressed)

the first person who answers both of the above will get the 125 points (i will split the points if nobody can answer both)

thankz 4 readin :)
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

C#.NET uses the KeyPress() event.
From the horses mouth:

When creating an application that accepts the user's keystrokes, you may also want to monitor for modifier keys such as the SHIFT, ALT, and CTRL keys. When a modifier key is pressed in combination with other keys, or with mouse clicks, your application can respond appropriately — the letter S may simply cause an "S" to appear on the screen, but if CTRL+S is pressed, the current document may be saved.

To determine which modifier key was pressed

Use the bitwise AND operator (And in Visual Basic, & in Visual C#) with the ModifierKeys property and a value of the Keys enumeration to determine which modifier key was pressed. (ModifierKeys is a shared member of the Control class; for more information on shared members, see Shared Members.)
' Visual Basic
Private Sub button1_KeyPress(ByVal sender As Object, ByVal e As _
System.Windows.Forms.KeyPressEventArgs) Handles button1.KeyPress
   If (Control.ModifierKeys And Keys.Shift) = Keys.Shift Then
      MessageBox.Show("Pressed " & Keys.Shift)
   End If
End Sub

// C#
private void button1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) {
   if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift) {
     MessageBox.Show("Pressed " + Keys.Shift);
See Also
Keys Enumeration | Control.ModifierKeys Property

death_befo_dishonorAuthor Commented:
lolz but this dosnt help me at all coz i want to use the windows api :(
You can still call Win32 API routines from within C#.NET.

This should help:
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

More samples:

"You'll find that the hardest part of working with the API in .NET is how to build the proper api call in C#. Since unmanaged code and managed code don't use the same types, you must be very specific in telling .NET how to marshal your code and that is totally an art." from:


A useful download:

All you might need from Win32API:

Here's the Win32 class library, to wit, those portions exposed via .NET.

For everything else you'll need a DLLImport.
Now that you've gone through all of that, if your intent was to intercept keystrokes not intended for any of your controls, you'll have to do that outside of .NET code.

The way to do that is with SetWindowsHookEx() to register a KeyboardProc callback to handle WH_KEYBOARD messages or a LowLevelKeyboardProc callback to handle WH_KEYBOARD_LL messages before they're directed to their intended destinations - and the registered CallWndProc can't be managed (.NET) code.
Oops, I left off:

You'll have to put all of that in a DLL that you then get to via a DLLImport.

death_befo_dishonorAuthor Commented:
that is exactly what i want 2 do... i attempted to do it using GetAsyncKeyState() but this is unbelivably messy coz i have to use a timer and... well that dosnt really matter.

so what is parameters does the SetWindowsHookEx() function use??

HHOOK SetWindowsHookEx(
  int idHook,                 // in your case, this would be WH_CALLWNDPROC
  HOOKPROC lpfn,         // address of hook procedure
  HINSTANCE hMod,      // handle to application instance
  DWORD dwThreadId   // identity of thread to install hook for

For that idHook, the hook procedure specified by lpfn must be a CallWndProc:

whose third parameter is a CWPSTRUCT that contains the  lParam, wParam, message, and hwnd that the OS message queue will pass on to the intended recipient.

death_befo_dishonorAuthor Commented:
how does that work exactly... i assume that one of thost varibles is the character that has been pressed... which one?? what do u mean by the address?
death_befo_dishonorAuthor Commented:
also do i have to import user32.dll or a different 1?
death_befo_dishonorAuthor Commented:
could u send me the code to use this and then i will be able to figure out what is going on

thankz... suma
I think you missed the point - you have to import the non-.NET dll YOU write that does the hooking.

Something else you haven't considered is getting the keystroke info back to the .NET code.  The objective of finding out about ALL keystrokes, not just those intended for your controls, requires monitoring the Windows message queue - something .NET simply does not do.  Indeed, the only event notifications .NET supports are those intended for the program.  In this case, the best you could do would be to buffer up whatever key press messages are caught and pass them back en masse whenever the appropriate DLL entry point is called by a timer routine in the .NET code - and if your timer interrupt is short enough to come close to reality, you slow up everything else.

This is one of the intended consequences of .NET's 'Managed Code' - "let's make it a bit easier to do lots of things while keeping most people out of the OS so they can't muck things up, and, listen up all you point haired managers, this means you can get by with less expensive programmers."

Note that if you were doing this as a 'standard' Windows program, it would be LOTS easier.

Also, I don't mean to offend, but if you don't know what is meant by 'address of the hook procedure' there will be much, much  else that won't be understood.
death_befo_dishonorAuthor Commented:
so i got to write the code inside the dll... can this be in any language (i only know vb & c#).

how do i make a standard windows program (what language)

there is already **** i dont understand man... managed code, unmanaged code...
death_befo_dishonorAuthor Commented:
ok ive done some research on hooks and what i want to do is make a global hook that fires every time a key is pressed.

im told that to do this i need to make a dll file that instalizes the hook and an .exe file which loads the dll file and saves the data to a txt file.

but it appears that visual c# .net cannot create a dll file (c++ can but i dont know it)

can any1 tell me:

1 how to create the dll file
2 what to put in it
3 how to create an event (in the exe file) that fires when the hook returns
4 how to remove the hook when im done (im told that this is necessary to free up system resources)

i guess anybody who tellz me all that deserves more than 130 points but that all i got (dam)
death_befo_dishonorAuthor Commented:
i now know how to make the dll using c#

i need to know:

>>what to put in it
>>how to return the keys to my exe file
>>how to remove the hook and where (do i remove it from the dll or the exe)
Let's take little steps.

You mentioned you have VB, so let's first use that to get a key hooker running.  Here's some VB that uses SetWindowsHookEx() to catch WH_CBT messages.  See if you can use what was presented above to modify it top capture key stroke messages.

death_befo_dishonorAuthor Commented:
i had a look through the code but i'll have to borrow the visual basic cd from my mate coz i dont have it installed anymo (also i havnt used vb for ages so im not very familiar with it)

i think the first step would be calling a function from a dll file, then i can make the hook function and put it in the dll file

im having a little trouble accessing the dll from an exe:

i put this inside a dll file:

using System;

class f
       public static long add(long x, long y)

i then moved the dll file to c:\windows\system32\

in my exe file, i sucessfully import the dll [DllImport("suma.dll")]  (no problems with this part)

but then i need to declare the function:

static extern long f.add(long x, long y);

but it wont let me do this so i changed it to: static extern add(long x, long y);

but then when i try to call it from my code long d=add(3,4); it gives me an error no entry point called add in suma.dll

hmmm im either declaring the function wrong or what i put in the dll file is incorrect

and ideas?
Well, you got one on me.  I had no idea C#.NET could create a DLL.

How did you create it?

Could you post the full souirce?
death_befo_dishonorAuthor Commented:
just put the code u want in the dll into a code file (*.cs)

then use the command line compiler as follows:

csc /input:library /out:YourFileName.dll FullPathOfTheCodeFile

csc /input:library /out:suma.dll c:\functions.cs

i was just surfing when i came across this article:
Well, you live and learn.

In any case, recall

" you have to import the non-.NET dll YOU write that does the hooking."

The DLL that does the hooking has to be NON-.NET, i.e., not managed code, so since you don't do C, it'll have to be a VB dll.

I going to be down for a few hours, I'll check back then.
death_befo_dishonorAuthor Commented:
god damn.... this creates a major problem 4 me:

i have vb .net but obviously that wont be of any use. i dug out a book which has a the 'working model edition' of vb 6 but it cant make exe's so even if i knew how to make dlls in vb i dont think id be able to do it with that version. seeingz as my friend (who has the full version of vb 6) lives in sydney and is currently visiting lanka, i dont think ima be able to get the full version of vb6 for AGES. maybe its time to give up :(
It is worth noting that MSVS.NET will create 'standard' (what MSVS.NET call C++) Windows EXEs and DLLs (i.e., it's just like having the MSVC 6).  You've already got a leg up on it with C#.NET, so the language per se shouldn't be a problem.  

Fortunately, there's about 7 gazillion times more sample code (and books)  available than for .NET.  If you feel like going ahead on that route, there will be two tough parts:

1) Instead of calling methods in the .NET manner, you'll have to learn the 'old' way*
thingy.length()   =>    strlen(thingy)
.format()           =>    sprintf()
and the list goes on.

* Actually, what to many is 'old' is still quite the standard.  .NET hasn't quite caught on as much as MS would have liked.  The requirement for the .NET environment has been a show stopper to many, as have its limitations, some of which you've seen here.  [Cook's aphorism #63: The hardest language to learn is your second one.  You'll eventually realize they're all alike.]

Just as the old farts have to learn the .NET method names, you'll have to learn the library calls.  But there's nothing new there.  The life of a programmer is one of constantly adapting to different environments, and the more tools you have hung on your belt, the more versitile and marketable you'll be.

2) I've changed my mind.  I don't think this part will be hard to deal with.  Although the initial layout of a Win32 program is different from .NET, the compiler generates most of it for you.  Both are event driven, you just get the events in a slightly different manner (one big SWITCH with CASEs for desired events - no big deal).
death_befo_dishonorAuthor Commented:
r u saying that there might be a way to program the hook using c# .net??

do u have msn messenger if so add me:
death_befo_dishonorAuthor Commented:
good news... i got a local hook working in c# :) it keeps track of the co-ordinates of the mouse (only when its over the form tho coz its local ofcause but its still a working hook)

ima try all different types of hooks so that when i get vb6 full version i can make a sick keylogger
Bring up Visual Studio .NET
Select New Project
Select Visual C++ Projects
Then select MFC Application, MFC DLL, or Win32 Project
death_befo_dishonorAuthor Commented:
for what? all those projects r still .net or as y'all puter-ppl call it "managed"

what r they used for anywayz?
seeingz az i got 2 give out these 130 points... if u will post the source code for a local windows keypress hook commentated for ppl like me who dont know what they r talking about ill give yo the points :)

laterz... suma
(in c# because thats the only language i know really well)
"for what? all those projects r still .net or as y'all puter-ppl call it "managed""

But that was the point, the MFC Application, MFC DLL, and Win32 projects are NOT managed code.

In any case, I'll post some code later today.
death_befo_dishonorAuthor Commented:
OMG!! they r not managed!! that is really awesome coz i was even considering learning python :) well allz cool... if u post the code i should b able to figure out every thing else over time...

In your c# code

add a keypress event handler definition for each control

textbox1.KeyDown += new System.Windows.Forms.KeyEventHandler(keyDown);

Then add the handler:
private void keyDown(object sender, KeyEventArgs e)
...e.KeyData has the keystroke

I'll post sample Win32 hook code later tonight.

Here's an MFC example that shows several hooks, WH_KEYBOARD among them, along with the intrepretation of the key press message and the identification of keys:

Moreover, it's a DLL, so you get to see what the structure of a DLL looks like.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
death_befo_dishonorAuthor Commented:
thanks man... i figure ima get accustomed wit hooks and when im good at that ill work out how to make a dll using c++...
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Editors IDEs

From novice to tech pro — start learning today.