Question

C++ .net (CLR) use Hotkey for Show/Hide Form

Asked by: seek1338

Hello!

I am very new c++ Programmer i have read a book and now try to writte my first Program using Mysql Connection.

My Problem is i want to make a Timer or new Thread that search after F4 pressed and then call a Function to Hide or Show the Main Form.

Since 4 Days i am searching for a function that can do that. In .net i found the System::Windows::Input namespace for WPF i use that in c++ by including the dll and the WindowsBase, but i dont found a solution.

Second thing i found are the Hooks now i am trying to implement this WINAPI in my c++ .net use a Thread with a while(true) for check every 5 ms the state.

I need a sample code how i can use this HOOKS in my .net projekt. Look at Code i Post the Thread. But i dont know how i can use the Dllimport.

That have to be a possibiltiy to make a easy if check like this:
while(true) {
  Thread::Sleep(5);   // wait 5ms to dont overload the prozessor
   if(checkKeyState(F4))
     //to this...
  }

I hope anyone can give me a code sample or a link to a code sample where this is explain because i dont found for c++ clr anything like this.

Thanks for your Help.

// Call Thread Code:
#include "keyEventThread.h"
 
Thread^ keyThread = gcnew Thread( gcnew ThreadStart( &keyEventThread::waitOnKey ) );
keyThread->SetApartmentState(ApartmentState::STA);
keyThread->Start();
 
 
// THREAD FILE "keyEventThread.h":
#pragma once
using namespace System;
using namespace System::Windows;
using namespace System::Threading;
using namespace System::Runtime::InteropServices;
 
[DllImport("User32.dll", EntryPoint = "SetWindowsHookEx")]
extern "C" long SetWindowsHookEx(long HookID, HookProc^ lpfn, IntPtr hInstance, long ThreadID);
 
[DllImport("User32.dll", EntryPoint = "CallNextHookEx")]
extern "C" long CallNextHookEx(long HookID, long iCode, IntPtr wParam, IntPtr lParam);
 
[DllImport("User32.dll", EntryPoint = "UnhookWindowsHookEx")]
extern "C" bool UnhookWindowsHookEx(long HookID);
 
//CLASS Managed
ref class keyEventThread  
{
public:
 static void waitOnKey() {
 while(true) {
    Thread::Sleep(5);
    /* Check here for F4 if pressed */
    // SetWindowsHookEx(WH_KEYBOARD_LL,0, // I dont know how to use The WinApi
    }
 }
};

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-08-03 at 03:21:26ID24621126
Tags

Hooks

,

Hotkey

Topics

Microsoft Visual C++.Net

,

C++ Programming Language

,

.NET Framework 3.x versions

Participating Experts
2
Points
500
Comments
14

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. OVERLOADING
    I have a question I am trying to make an ISBN which is a code of 10 characters separated by dashes, Should I try to implement my own ISBN by string class? or should I use other method? Also this require Overloading? Thanks Leo
  2. Howto write dll in c# that can be accessed by [DllImport]…
    I have to create a dll in c#, that can be accesed by DllImport, because it is my theory, that I then will be able to acces the dll from Navision XAL also. I am well aware that there are many easier ways to acces dlls, in c# and .net, but since Navision XAL can not use COM ob...
  3. Overloading APIs
    This is something simple I guess.I have been using API functions in my VB 6.0 project. Like for ex, Private Declare Function ReadFile Lib "kernel32" (ByVal hFile As Integer, ByRef lpBuffer As Any, ByVal nNumberOfBytesToRead As Integer, ByRef lpNumberOfBytesRead As ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: LaindowPosted on 2009-08-03 at 03:49:01ID: 25003208

Hi,
  Make Windows hooks when you just start programming it hard. + Make hook just for pop-up your form that bad stile of programming. Put tray icon for your application into tray and let user get your form when he will need.

 

by: seek1338Posted on 2009-08-03 at 05:13:05ID: 25003612

Hello!

Thanks for the answer. I am not a completely a beginner because i understand the most of the code I had writte this project last Year in Vb.net.

Now i decide to rewrite it it in c++ .net and make some changes in design and functions.

Connection for MySql DB and more but i need this function and i think its only possible over hooks. And what i am dont need are 20 Sites code for 1 function, i mean i need only this function F4 Hide/Show.

I Hope you understand my poor English :)

Thanks. Seek

 

by: LaindowPosted on 2009-08-03 at 05:43:23ID: 25003798

If I will show how to show your Form by run your application second time or some another little application will it resolver your issue ? It much more easy. Set hook based on C# or VB required much more. Hook it not timer - your DLL will inject into all processes and it will slow down system. Unmanagement C++ better to do thing like that. You can put shortcut on it little program on your desktop assign hot key for it and get same result without any hooks :) Your English fine :)

 

by: seek1338Posted on 2009-08-03 at 10:38:52ID: 25006576

Hmm ok i understand now what hooks are.

But i dont want create any dll and inject this to all programs to get all messages. I only want to get the state of a key on the keyboard and if state is pressed do something.

Thats not possible that hooks are the only way to do that. What is with getasynckeystate() ? I cant believe thats no way to only read the keyboard input without inject all the system. In my Vb.net Project i have used the API below.

If there are really no other possibilities as to inject the system i hope that you can explain me how i can create a Systray Icon to control the Appearance over the Form.

Thanks a lot!

## My VB Code from last year ( was a copy&past from any site script/tutorial site: ##
 
    Implements IMessageFilter
 
    Private Declare Function RegisterHotKey Lib "user32" ( _
        ByVal Hwnd As IntPtr, _
        ByVal ID As Integer, _
        ByVal Modifiers As Integer, _
        ByVal Key As Integer) _
    As Integer
 
    Private Declare Function UnregisterHotKey Lib "user32" ( _
        ByVal Hwnd As IntPtr, _
        ByVal ID As Integer) _
    As Integer
 
    Private Declare Function GlobalAddAtom Lib "kernel32" Alias "GlobalAddAtomA" ( _
        ByVal IDString As String) _
    As Short
 
    Private Declare Function GlobalDeleteAtom Lib "kernel32" ( _
        ByVal Atom As Short) _
    As Short

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:

Select allOpen in new window

 

by: eeBrandonPosted on 2009-08-03 at 17:02:47ID: 25009538

I think the form has a property called "KeyPreview."  This MSFT kb article might help.

http://support.microsoft.com/kb/839201

I can easily tell you how to do this is in native code, but my .NET is not up to par =)

 

by: seek1338Posted on 2009-08-03 at 22:55:31ID: 25010936

Hi eeBrandon  i think the code in your link is only for local (only Form) Hotkeys. I need it for the completely System, because if the form is not visible or not focused i cant use the to control the form.

Do you mean thats right what i think?

private: System::Void Form1_Load(System::Object *  sender, System::EventArgs *  e)
{
	// Set these when the form loads:
	// Have the form capture keyboard events first.
	this->KeyPreview = true;
	// Assign the event handler to the form.
	this->KeyDown += new System::Windows::Forms::KeyEventHandler(this, FormKeyDown);
	// Assign the event handler to the text box.
	this->textBox1->KeyDown += new System::Windows::Forms::KeyEventHandler(this, TextBoxKeyDown);
}
private: System::Void FormKeyDown(System::Object *  sender, System::Windows::Forms::KeyEventArgs *  e)
{
	if(e->Alt && e->KeyCode == System::Windows::Forms::Keys::F){
		// When the user presses both the 'Alt' key and 'F' key,
		// KeyPreview is set to False, and a message appears.
		// This message is only displayed when KeyPreview is set to True.
		this->KeyPreview = false;
		MessageBox::Show(this,"KeyPreview is True, and this came from the FORM");
	}
}
private: System::Void TextBoxKeyDown(System::Object *  sender, System::Windows::Forms::KeyEventArgs *  e)
{
	if(e->Alt && e->KeyCode == System::Windows::Forms::Keys::F){
		// When the user presses both the 'Alt' key and 'F' key,
		// KeyPreview is set to True, and a message appears.
		// This message is only displayed when KeyPreview is set to False.
		this->KeyPreview = true;
		MessageBox::Show(this,"KeyPreview is False, and this came from the CONTROL");
	}
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:

Select allOpen in new window

 

by: LaindowPosted on 2009-08-04 at 01:24:29ID: 25011504

Ok I got your point of view. You don't want just show form you wanna do any action when user click some keys combination in any application. It can't be done by using only 1 function it required combination DLL + EXE also that can be done only under Win API and C++. Framework can't do it. You can wrap API by framework but it still will be API calls. If you not hurry I can show how to do it on weekends.

 

by: seek1338Posted on 2009-08-04 at 02:20:34ID: 25011726

I only need it for one Hotkey to show/hide the Form.

In VB.net there was 4,5 functions to handle the API Call i know that c++ is more code intensive but i dont want to use a dll. If that in VB.net works without dll why it dont works in C++.net, its the same API or not ;-) ?

I have time thats not the problem i prefer to use a non dll solution if its possible. I know now that .net is only better for c# and i will be start to learn c++ MFC for windows programming and c# for .net :-)

 

by: LaindowPosted on 2009-08-04 at 02:44:30ID: 25011842

Hi,
 MFC not good at all :) .NET same for all languages - you can use exactly same functions language don't change anything. I recommend you have a look on this sample. It code hook all input from keyboard you just need to choose what key are you want :) That different way to control user input but it can work better for you because use only C# code. I prefer more low level but I also prefer C++ like programming language :) If you will have a questions about sample I can help you.

http://www.codeproject.com/KB/system/rawinput.aspx?display=PrintAll

 

by: seek1338Posted on 2009-08-04 at 03:56:32ID: 25012221

Laindow i think thats what i am searching, but its in c# my skill is not enought to rewritte all in c++. And i think there are to much code what i dont need, i will try to cut it :-)

I write some Code below maybe you can help me to write it in c++ format?

Thanks for you help.

Dont know what StructLayouts are?
 
        [StructLayout(LayoutKind.Explicit)]
        internal struct RAWINPUT
        {
            [FieldOffset(0)]
            public RAWINPUTHEADER header;
            [FieldOffset(16)]
            public RAWMOUSE mouse;
            [FieldOffset(16)]
            public RAWKEYBOARD keyboard;
            [FieldOffset(16)]
            public RAWHID hid;
        }

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:

Select allOpen in new window

 

by: LaindowPosted on 2009-08-04 at 04:30:30ID: 25012418

Hi,
 In C++ it just like I show below - author use so much special syntax because he tried to make C# structure same like it in C++. If you use .NET anyway may be better for you to write everything in C# ? If you use .NET in C++ you don't have any performance advantage :)
And I think RAWINPUT already defined in C++.

struct RAWINPUT
        {
            public RAWINPUTHEADER header;
            public RAWMOUSE mouse;
            public RAWKEYBOARD keyboard;
            public RAWHID hid;
        }

                                              
1:
2:
3:
4:
5:
6:
7:

Select allOpen in new window

 

by: seek1338Posted on 2009-08-04 at 05:22:11ID: 25012785

So mostly are done, but i have 44 Compiler Failure and i think most of them in relation with the struct`s

I put the code below maybe you can overview this? Thanks.

#pragma once
 
using namespace System;
using namespace System::Collections;
using namespace System::IO;
using namespace System::Runtime::InteropServices;
using namespace System::Windows::Forms;
using namespace Microsoft::Win32;
 
namespace test_key
{
 
 
	/// <summary>
	/// Handles raw input from keyboard devices.
	/// </summary>
	public ref class InputDevice sealed
	{
		#pragma region const definitions
 
		// The following constants are defined in Windows.h
 
	private:
		literal int RIDEV_INPUTSINK = 0x00000100;
		literal int RID_INPUT = 0x10000003;
 
		literal int FAPPCOMMAND_MASK = 0xF000;
		literal int FAPPCOMMAND_MOUSE = 0x8000;
		literal int FAPPCOMMAND_OEM = 0x1000;
 
		literal int RIM_TYPEMOUSE = 0;
		literal int RIM_TYPEKEYBOARD = 1;
		literal int RIM_TYPEHID = 2;
 
		literal int RIDI_DEVICENAME = 0x20000007;
 
		literal int WM_KEYDOWN = 0x0100;
		literal int WM_SYSKEYDOWN = 0x0104;
		literal int WM_INPUT = 0x00FF;
		literal int VK_OEM_CLEAR = 0xFE;
		literal int VK_LAST_KEY = VK_OEM_CLEAR; // this is a made up value used as a sentinel
 
		#pragma endregion const definitions
 
		#pragma region structs & enums
 
		/// <summary>
		/// An enum representing the different types of input devices.
		/// </summary>
	public:
		enum class DeviceType
		{
			Key,
			Mouse,
			OEM
		};
 
		/// <summary>
		/// Class encapsulating the information about a
		/// keyboard event, including the device it
		/// originated with and what key was pressed
		/// </summary>
	public:
		ref class DeviceInfo
		{
		public:
			System::String ^deviceName;
			System::String ^deviceType;
			IntPtr deviceHandle;
			System::String ^Name;
			System::String ^source;
			System::UInt16 key;
			System::String ^vKey;
		};
 
		#pragma region Windows.h structure declarations
 
		// The following structures are defined in Windows.h
 
 
		struct RAWINPUTDEVICELIST {
			IntPtr hDevice;
			int dwType;
		}
 
 
		struct RAWINPUT {
			RAWINPUTHEADER header;
			RAWMOUSE mouse;
			RAWKEYBOARD keyboard;
			RAWHID hid;
		}
 
		struct RAWINPUTHEADER {
			int dwType;
			int dwSize;
			IntPtr hDevice;
			int wParam;
		}
 
 
		struct RAWHID {
			int dwSizHid;
			int dwCount;
		}
 
		struct BUTTONSSTR {
			System::UInt16 usButtonFlags;
			System::UInt16 usButtonData;
		}
 
		struct RAWMOUSE {
			System::UInt16 usFlags;
			System::UInt32 ulButtons;
			BUTTONSSTR buttonsStr;
			System::UInt32 ulRawButtons;
			int lLastX;
			int lLastY;
			System::UInt32 ulExtraInformation;
		}
 
		struct RAWKEYBOARD 	{
			System::UInt16 MakeCode;
			System::UInt16 Flags;
			System::UInt16 Reserved;
			System::UInt16 VKey;
			System::UInt32 Message;
			System::UInt32 ExtraInformation;
		}
 
 
		struct RAWINPUTDEVICE {
			System::UInt16 usUsagePage;
			System::UInt16 usUsage;
			int dwFlags;
			IntPtr hwndTarget;
		}
		#pragma endregion Windows.h structure declarations
 
 
		#pragma endregion structs & enums
 
		#pragma region DllImports
 
		[DllImport("User32.dll")]
		static System::UInt32 GetRawInputDeviceList(IntPtr pRawInputDeviceList, System::UInt32 %uiNumDevices, System::UInt32 cbSize);
 
		[DllImport("User32.dll")]
		static System::UInt32 GetRawInputDeviceInfo(IntPtr hDevice, System::UInt32 uiCommand, IntPtr pData, System::UInt32 %pcbSize);
 
		[DllImport("User32.dll")]
		static bool RegisterRawInputDevices(array<RAWINPUTDEVICE> ^pRawInputDevice, System::UInt32 uiNumDevices, System::UInt32 cbSize);
 
		[DllImport("User32.dll")]
		static System::UInt32 GetRawInputData(IntPtr hRawInput, System::UInt32 uiCommand, IntPtr pData, System::UInt32 %pcbSize, System::UInt32 cbSizeHeader);
 
		#pragma endregion DllImports
 
		#pragma region Variables and event handling
 
		/// <summary>
		/// List of keyboard devices. Key: the device handle
		/// Value: the device info class
		/// </summary>
	private:
		Hashtable ^deviceList;
 
		/// <summary>
		/// The delegate to handle KeyPressed events.
		/// </summary>
		/// <param name="sender">The object sending the event.</param>
		/// <param name="e">A set of KeyControlEventArgs information about the key that was pressed and the device it was on.</param>
	public:
		delegate void DeviceEventHandler(System::Object ^sender, KeyControlEventArgs ^e);
 
		/// <summary>
		/// The event raised when InputDevice detects that a key was pressed.
		/// </summary>
		event DeviceEventHandler ^KeyPressed;
 
		/// <summary>
		/// Arguments provided by the handler for the KeyPressed
		/// event.
		/// </summary>
	public:
		ref class KeyControlEventArgs : EventArgs
		{
		private:
			DeviceInfo ^m_deviceInfo;
			DeviceType m_device;
 
		public:
			KeyControlEventArgs(DeviceInfo ^dInfo, DeviceType device)
			{
				m_deviceInfo = dInfo;
				m_device = device;
			}
 
			KeyControlEventArgs()
			{
			}
 
			property DeviceInfo ^Keyboard
			{
				DeviceInfo ^get()
				{
					return m_deviceInfo;
				}
				void set(DeviceInfo ^value)
				{
					m_deviceInfo = value;
				}
			}
 
			property DeviceType Device
			{
				DeviceType get()
				{
					return m_device;
				}
				void set(DeviceType value)
				{
					m_device = value;
				}
			}
		};
 
		#pragma endregion Variables and event handling
 
		#pragma region InputDevice( IntPtr hwnd )
 
		/// <summary>
		/// InputDevice constructor; registers the raw input devices
		/// for the calling window.
		/// </summary>
		/// <param name="hwnd">Handle of the window listening for key presses</param>
	public:
		InputDevice(IntPtr hwnd)
		{
			//Create an array of all the raw input devices we want to 
			//listen to. In this case, only keyboard devices.
			//RIDEV_INPUTSINK determines that the window will continue
			//to receive messages even when it doesn't have the focus.
			InitializeInstanceFields();
			array<RAWINPUTDEVICE> ^rid = gcnew array<RAWINPUTDEVICE>(1);
 
			rid[0].usUsagePage = 0x01;
			rid[0].usUsage = 0x06;
			rid[0].dwFlags = RIDEV_INPUTSINK;
			rid[0].hwndTarget = hwnd;
 
			if(!RegisterRawInputDevices(rid, safe_cast<System::UInt32>(rid->Length), safe_cast<System::UInt32>(Marshal::SizeOf(rid[0]))))
			{
				throw gcnew ApplicationException("Failed to register raw input device(s).");
			}
		}
 
		#pragma endregion InputDevice( IntPtr hwnd )
 
		#pragma region ReadReg( string item, ref bool isKeyboard )
 
		/// <summary>
		/// Reads the Registry to retrieve a friendly description
		/// of the device, and determine whether it is a keyboard.
		/// </summary>
		/// <param name="item">The device name to search for, as provided by GetRawInputDeviceInfo.</param>
		/// <param name="isKeyboard">Determines whether the device's class is "Keyboard".</param>
		/// <returns>The device description stored in the Registry entry's DeviceDesc value.</returns>
	private:
		System::String ^ReadReg(System::String ^item, bool %isKeyboard)
		{
			// Example Device Identification string
			// @"\??\ACPI#PNP0303#3&13c0b0c5&0#{884b96c3-56ef-11d1-bc8c-00a0c91405dd}";
 
			// remove the \??\
			item = item->Substring(4);
 
			array<System::String^> ^split = item->Split('#');
 
			System::String ^id_01 = split[0]; // ACPI (Class code)
			System::String ^id_02 = split[1]; // PNP0303 (SubClass code)
			System::String ^id_03 = split[2]; // 3&13c0b0c5&0 (Protocol code)
			//The final part is the class GUID and is not needed here
 
			//Open the appropriate key as read-only so no permissions
			//are needed.
			RegistryKey ^OurKey = Registry::LocalMachine;
 
			System::String ^findme = System::String::Format("System\\CurrentControlSet\\Enum\\{0}\\{1}\\{2}", id_01, id_02, id_03);
 
			OurKey = OurKey->OpenSubKey(findme, false);
 
			//Retrieve the desired information and set isKeyboard
			System::String ^deviceDesc = safe_cast<System::String^>(OurKey->GetValue("DeviceDesc"));
			System::String ^deviceClass = safe_cast<System::String^>(OurKey->GetValue("Class"));
 
			if(deviceClass->ToUpper()->Equals("KEYBOARD"))
			{
				isKeyboard = true;
			}
			else
			{
				isKeyboard = false;
			}
			return deviceDesc;
		}
 
		#pragma endregion ReadReg( string item, ref bool isKeyboard )
 
		#pragma region int EnumerateDevices()
 
		/// <summary>
		/// Iterates through the list provided by GetRawInputDeviceList,
		/// counting keyboard devices and adding them to deviceList.
		/// </summary>
		/// <returns>The number of keyboard devices found.</returns>
	public:
		int EnumerateDevices()
		{
 
			int NumberOfDevices = 0;
			System::UInt32 deviceCount = 0;
			int dwSize = (Marshal::SizeOf(RAWINPUTDEVICELIST::typeid));
 
			// Get the number of raw input devices in the list,
			// then allocate sufficient memory and get the entire list
			if(GetRawInputDeviceList(IntPtr::Zero, deviceCount, safe_cast<System::UInt32>(dwSize)) == 0)
			{
				IntPtr pRawInputDeviceList = Marshal::AllocHGlobal(safe_cast<int>(dwSize * deviceCount));
				GetRawInputDeviceList(pRawInputDeviceList, deviceCount, safe_cast<System::UInt32>(dwSize));
 
				// Iterate through the list, discarding undesired items
				// and retrieving further information on keyboard devices
				for (int i = 0; i < deviceCount; i++)
				{
					DeviceInfo ^dInfo;
					System::String ^deviceName;
					System::UInt32 pcbSize = 0;
 
					RAWINPUTDEVICELIST rid = safe_cast<RAWINPUTDEVICELIST>(Marshal::PtrToStructure(IntPtr((pRawInputDeviceList.ToInt32() + (dwSize * i))), RAWINPUTDEVICELIST::typeid));
 
					GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, IntPtr::Zero, pcbSize);
 
					if (pcbSize > 0)
					{
						IntPtr pData = Marshal::AllocHGlobal(safe_cast<int>(pcbSize));
						GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, pData, pcbSize);
						deviceName = safe_cast<System::String^>(Marshal::PtrToStringAnsi(pData));
 
						// Drop the "root" keyboard and mouse devices used for Terminal 
						// Services and the Remote Desktop
						if (deviceName->ToUpper()->Contains("ROOT"))
						{
							continue;
						}
 
						// If the device is identified in the list as a keyboard or 
						// HID device, create a DeviceInfo object to store information 
						// about it
						if (rid.dwType == RIM_TYPEKEYBOARD || rid.dwType == RIM_TYPEHID)
						{
							dInfo = gcnew DeviceInfo();
 
							dInfo->deviceName = safe_cast<System::String^>(Marshal::PtrToStringAnsi(pData));
							dInfo->deviceHandle = rid.hDevice;
							dInfo->deviceType = GetDeviceType(rid.dwType);
 
							// Check the Registry to see whether this is actually a 
							// keyboard, and to retrieve a more friendly description.
							bool IsKeyboardDevice = false;
							System::String ^DeviceDesc = ReadReg(deviceName, IsKeyboardDevice);
							dInfo->Name = DeviceDesc;
 
							// If it is a keyboard and it isn't already in the list,
							// add it to the deviceList hashtable and increase the
							// NumberOfDevices count
							if (!deviceList->Contains(rid.hDevice) && IsKeyboardDevice)
							{
								NumberOfDevices++;
								deviceList->Add(rid.hDevice, dInfo);
							}
						}
						Marshal::FreeHGlobal(pData);
					}
				}
 
 
				Marshal::FreeHGlobal(pRawInputDeviceList);
 
				return NumberOfDevices;
 
			}
			else
			{
				throw gcnew ApplicationException("An error occurred while retrieving the list of devices.");
			}
 
		}
 
		#pragma endregion EnumerateDevices()
 
		#pragma region ProcessInputCommand( Message message )
 
		/// <summary>
		/// Processes WM_INPUT messages to retrieve information about any
		/// keyboard events that occur.
		/// </summary>
		/// <param name="message">The WM_INPUT message to process.</param>
		void ProcessInputCommand(Message message)
		{
			System::UInt32 dwSize = 0;
 
			// First call to GetRawInputData sets the value of dwSize,
			// which can then be used to allocate the appropriate amount of memory,
			// storing the pointer in "buffer".
			GetRawInputData(message.LParam, RID_INPUT, IntPtr::Zero, dwSize, safe_cast<System::UInt32>(Marshal::SizeOf(RAWINPUTHEADER::typeid)));
 
			IntPtr buffer = Marshal::AllocHGlobal(safe_cast<int>(dwSize));
			try
			{
				// Check that buffer points to something, and if so,
				// call GetRawInputData again to fill the allocated memory
				// with information about the input
				if (buffer != IntPtr::Zero && GetRawInputData(message.LParam, RID_INPUT, buffer, dwSize, safe_cast<System::UInt32>(Marshal::SizeOf(RAWINPUTHEADER::typeid))) == dwSize)
				{
					// Store the message information in "raw", then check
					// that the input comes from a keyboard device before
					// processing it to raise an appropriate KeyPressed event.
 
					RAWINPUT raw = safe_cast<RAWINPUT>(Marshal::PtrToStructure(buffer, RAWINPUT::typeid));
 
					if (raw.header.dwType == RIM_TYPEKEYBOARD)
					{
						// Filter for Key Down events and then retrieve information 
						// about the keystroke
						if (raw.keyboard.Message == WM_KEYDOWN || raw.keyboard.Message == WM_SYSKEYDOWN)
						{
 
							System::UInt16 key = raw.keyboard.VKey;
 
							// On most keyboards, "extended" keys such as the arrow or 
							// page keys return two codes - the key's own code, and an
							// "extended key" flag, which translates to 255. This flag
							// isn't useful to us, so it can be disregarded.
							if (key > VK_LAST_KEY)
							{
								return;
							}
 
							// Retrieve information about the device and the
							// key that was pressed.
							DeviceInfo ^dInfo = nullptr;
 
							if (deviceList->Contains(raw.header.hDevice))
							{
								Keys myKey;
 
								dInfo = safe_cast<DeviceInfo^>(deviceList[raw.header.hDevice]);
 
								myKey = safe_cast<Keys>(Enum::Parse(Keys::typeid, Enum::GetName(Keys::typeid, key)));
								dInfo->vKey = myKey.ToString();
								dInfo->key = key;
							}
							else
							{
								System::String ^errMessage = System::String::Format("Handle :{0} was not in hashtable. The device may support more than one handle or usage page, and is probably not a standard keyboard.", raw.header.hDevice);
								throw gcnew ApplicationException(errMessage);
							}
 
							// If the key that was pressed is valid and there
							// was no problem retrieving information on the device,
							// raise the KeyPressed event.
							if (KeyPressed != nullptr && dInfo != nullptr)
							{
								KeyPressed(this, gcnew KeyControlEventArgs(dInfo, GetDevice(message.LParam.ToInt32())));
							}
							else
							{
								System::String ^errMessage = System::String::Format("Received Unknown Key: {0}. Possibly an unknown device", key);
								throw gcnew ApplicationException(errMessage);
							}
						}
					}
				}
			}
			finally
			{
				Marshal::FreeHGlobal(buffer);
			}
		}
 
		#pragma endregion ProcessInputCommand( Message message )
 
		#pragma region DeviceType GetDevice( int param )
 
		/// <summary>
		/// Determines what type of device triggered a WM_INPUT message.
		/// (Used in the ProcessInputCommand method).
		/// </summary>
		/// <param name="param">The LParam from a WM_INPUT message.</param>
		/// <returns>A DeviceType enum value.</returns>
	private:
		DeviceType GetDevice(int param)
		{
			DeviceType deviceType;
 
			switch(safe_cast<int>((safe_cast<System::UInt16>(param >> 16)) & FAPPCOMMAND_MASK))
			{
				case FAPPCOMMAND_OEM:
					deviceType = DeviceType::OEM;
					break;
				case FAPPCOMMAND_MOUSE:
					deviceType = DeviceType::Mouse;
					break;
				default:
					deviceType = DeviceType::Key;
					break;
			}
 
			return deviceType;
		}
 
		#pragma endregion DeviceType GetDevice( int param )
 
		#pragma region ProcessMessage( Message message )
 
		/// <summary>
		/// Filters Windows messages for WM_INPUT messages and calls
		/// ProcessInputCommand if necessary.
		/// </summary>
		/// <param name="message">The Windows message.</param>
	public:
		void ProcessMessage(Message message)
		{
			switch(message.Msg)
			{
				case WM_INPUT:
				{
					ProcessInputCommand(message);
				}
				break;
			}
		}
 
		#pragma endregion ProcessMessage( Message message )
 
		#pragma region GetDeviceType( int device )
 
		/// <summary>
		/// Converts a RAWINPUTDEVICELIST dwType value to a string
		/// describing the device type.
		/// </summary>
		/// <param name="device">A dwType value (RIM_TYPEMOUSE, 
		/// RIM_TYPEKEYBOARD or RIM_TYPEHID).</param>
		/// <returns>A string representation of the input value.</returns>
	private:
		System::String ^GetDeviceType(int device)
		{
			System::String ^deviceType;
			switch(device)
			{
				case RIM_TYPEMOUSE:
					deviceType = "MOUSE";
					break;
				case RIM_TYPEKEYBOARD:
					deviceType = "KEYBOARD";
					break;
				case RIM_TYPEHID:
					deviceType = "HID";
					break;
				default:
					deviceType = "UNKNOWN";
					break;
			}
			return deviceType;
		}
 
		#pragma endregion GetDeviceType( int device )
 
 
	private:
		void InitializeInstanceFields()
		{
			static bool initialized = false;
			if ( ! initialized)
			{
				deviceList = gcnew Hashtable();
			
				initialized = true;
			}
		}
		void m_KeyPressed(System::Object ^sender, InputDevice::KeyControlEventArgs ^e)
		{
			//Replace() is just a cosmetic fix to stop ampersands turning into underlines
			//lbHandle->Text = e->Keyboard->deviceHandle->ToString();
			//lbType->Text = e->Keyboard->deviceType;
			//lbName->Text = e->Keyboard->deviceName->Replace("&", "&&");
			//lbDescription->Text = e->Keyboard.Name;
			//lbKey->Text = e->Keyboard->key->ToString();
			//lbNumKeyboards->Text = NumberOfKeyboards.ToString();
			lbVKey->Text = e->Keyboard->vKey;
		}
	};
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:
265:
266:
267:
268:
269:
270:
271:
272:
273:
274:
275:
276:
277:
278:
279:
280:
281:
282:
283:
284:
285:
286:
287:
288:
289:
290:
291:
292:
293:
294:
295:
296:
297:
298:
299:
300:
301:
302:
303:
304:
305:
306:
307:
308:
309:
310:
311:
312:
313:
314:
315:
316:
317:
318:
319:
320:
321:
322:
323:
324:
325:
326:
327:
328:
329:
330:
331:
332:
333:
334:
335:
336:
337:
338:
339:
340:
341:
342:
343:
344:
345:
346:
347:
348:
349:
350:
351:
352:
353:
354:
355:
356:
357:
358:
359:
360:
361:
362:
363:
364:
365:
366:
367:
368:
369:
370:
371:
372:
373:
374:
375:
376:
377:
378:
379:
380:
381:
382:
383:
384:
385:
386:
387:
388:
389:
390:
391:
392:
393:
394:
395:
396:
397:
398:
399:
400:
401:
402:
403:
404:
405:
406:
407:
408:
409:
410:
411:
412:
413:
414:
415:
416:
417:
418:
419:
420:
421:
422:
423:
424:
425:
426:
427:
428:
429:
430:
431:
432:
433:
434:
435:
436:
437:
438:
439:
440:
441:
442:
443:
444:
445:
446:
447:
448:
449:
450:
451:
452:
453:
454:
455:
456:
457:
458:
459:
460:
461:
462:
463:
464:
465:
466:
467:
468:
469:
470:
471:
472:
473:
474:
475:
476:
477:
478:
479:
480:
481:
482:
483:
484:
485:
486:
487:
488:
489:
490:
491:
492:
493:
494:
495:
496:
497:
498:
499:
500:
501:
502:
503:
504:
505:
506:
507:
508:
509:
510:
511:
512:
513:
514:
515:
516:
517:
518:
519:
520:
521:
522:
523:
524:
525:
526:
527:
528:
529:
530:
531:
532:
533:
534:
535:
536:
537:
538:
539:
540:
541:
542:
543:
544:
545:
546:
547:
548:
549:
550:
551:
552:
553:
554:
555:
556:
557:
558:
559:
560:
561:
562:
563:
564:
565:
566:
567:
568:
569:
570:
571:
572:
573:
574:
575:
576:
577:
578:
579:
580:
581:
582:
583:
584:
585:
586:
587:
588:
589:
590:
591:
592:
593:
594:
595:
596:
597:
598:
599:
600:
601:
602:
603:
604:

Select allOpen in new window

 

by: LaindowPosted on 2009-08-04 at 05:35:05ID: 25012903

can you just give me project plz ?
Send it to laindow@hotmail.com
Don't forget remove rubbish files like .obj

 

by: seek1338Posted on 2009-08-08 at 02:19:30ID: 31610860

Thanks for your time and Help!

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...