Solved

windows API using c#

Posted on 2003-12-01
35
11,255 Views
Last Modified: 2013-12-14
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 :)
0
Comment
Question by:death_befo_dishonor
  • 17
  • 16
  • 2
35 Comments
 
LVL 22

Expert Comment

by:cookre
ID: 9855032
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
=====



0
 

Author Comment

by:death_befo_dishonor
ID: 9855368
lolz but this dosnt help me at all coz i want to use the windows api :(
0
 
LVL 22

Expert Comment

by:cookre
ID: 9855486
You can still call Win32 API routines from within C#.NET.

This should help:
http://www.csharphelp.com/archives/archive79.html
0
 
LVL 22

Expert Comment

by:cookre
ID: 9855552
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:
http://www.aspemporium.com/aspEmporium/cshrp/howtos/howto.asp?hid=9

Book:
http://www.programming123.com/detail/win32_api/win32_api_078214134X.html

A useful download:
http://www.codeproject.com/csharp/win32.asp

All you might need from Win32API:
http://msdn.microsoft.com/library/default.asp

0
 
LVL 22

Expert Comment

by:cookre
ID: 9855728
0
 
LVL 22

Expert Comment

by:cookre
ID: 9855770
Here's the Win32 class library, to wit, those portions exposed via .NET.

For everything else you'll need a DLLImport.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfmicrosoftwin32.asp
0
 
LVL 22

Expert Comment

by:cookre
ID: 9855842
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.
0
 
LVL 22

Expert Comment

by:cookre
ID: 9855847
Oops, I left off:

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



0
 

Author Comment

by:death_befo_dishonor
ID: 9863722
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??
0
 
LVL 22

Expert Comment

by:cookre
ID: 9863925

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/WinUI/WindowsUserInterface/Windowing/Hooks/HookReference/HookFunctions/SetWindowsHookEx.asp

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:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/WinUI/WindowsUserInterface/Windowing/Hooks/HookReference/HookFunctions/CallWndProc.asp

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.

0
 

Author Comment

by:death_befo_dishonor
ID: 9864046
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?
0
 

Author Comment

by:death_befo_dishonor
ID: 9864054
also do i have to import user32.dll or a different 1?
0
 

Author Comment

by:death_befo_dishonor
ID: 9864071
could u send me the code to use this and then i will be able to figure out what is going on

thankz... suma
0
 
LVL 22

Expert Comment

by:cookre
ID: 9864302
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.
0
 

Author Comment

by:death_befo_dishonor
ID: 9864370
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...
0
 

Author Comment

by:death_befo_dishonor
ID: 9864583
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)
0
 

Author Comment

by:death_befo_dishonor
ID: 9870017
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)
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 22

Expert Comment

by:cookre
ID: 9870333
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.
http://www.mvps.org/vbnet/index.html?code/hooks/messageboxhook.htm

0
 

Author Comment

by:death_befo_dishonor
ID: 9871161
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)
       {
               return(x+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?
0
 
LVL 22

Expert Comment

by:cookre
ID: 9871379
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?
0
 

Author Comment

by:death_befo_dishonor
ID: 9871453
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

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

i was just surfing when i came across this article:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cscon/html/vclrfbuildingdynamiclinkinglibrarydll.asp
0
 
LVL 22

Expert Comment

by:cookre
ID: 9871551
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.
0
 

Author Comment

by:death_befo_dishonor
ID: 9871638
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 :(
0
 
LVL 22

Expert Comment

by:cookre
ID: 9871951
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).
0
 

Author Comment

by:death_befo_dishonor
ID: 9872402
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: suma_ds@hotmail.com
0
 

Author Comment

by:death_befo_dishonor
ID: 9872481
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
0
 
LVL 22

Expert Comment

by:cookre
ID: 9872529
Bring up Visual Studio .NET
Select New Project
Select Visual C++ Projects
Then select MFC Application, MFC DLL, or Win32 Project
0
 

Author Comment

by:death_befo_dishonor
ID: 9872689
for what? all those projects r still .net or as y'all puter-ppl call it "managed"

what r they used for anywayz?
0
 
LVL 1

Expert Comment

by:suma_ds
ID: 9872902
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
0
 
LVL 1

Expert Comment

by:suma_ds
ID: 9872904
(in c# because thats the only language i know really well)
0
 
LVL 22

Expert Comment

by:cookre
ID: 9873098
"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.
0
 

Author Comment

by:death_befo_dishonor
ID: 9873667
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...

laterz
0
 
LVL 22

Expert Comment

by:cookre
ID: 9875117
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.




0
 
LVL 22

Accepted Solution

by:
cookre earned 130 total points
ID: 9877844
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:

http://www.cam.hi-ho.ne.jp/oishi/source/xkeymacsdll_cpp.html


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

0
 

Author Comment

by:death_befo_dishonor
ID: 9878633
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++...
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
Although it can be difficult to imagine, someday your child will have a career of his or her own. He or she will likely start a family, buy a home and start having their own children. So, while being a kid is still extremely important, it’s also …
The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…
The viewer will learn how to use and create new code templates in NetBeans IDE 8.0 for Windows.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now