Team Foundation Server Hosting
Skip Navigation Links
C# Corner Home
Forum Home
Latest 50
Unanswered
Win Prizes
All Time Leaders
Jump to CategoryExpand Jump to Category
Login 
    Welcome Guest!
 Search Forum For :  
X
 Login
Please login to submit a new post, reply and edit exiting posts, see user profiles, and access more features. If you are not a registered member, Register here.
User Id / Email:
Password:  
Forgot Password | Forgot UserName
   Home » C# Language » Mouse background hook
       
Author Reply
webb webbhelp
posted 7 posts
since Aug 30, 2010 
from

Mouse background hook

  Posted on: 30 Aug 2010       
Hi!

I am trying to hook mouseevents in the background but I don't get everything to work :/


public UserActivityHook actHook;
        private void mouseclicker_Load(object sender, EventArgs e)
        {
            actHook = new UserActivityHook(); // create an instance

            // hang on events
            actHook.OnMouseActivity+=new MouseEventHandler(MouseMoved);
            actHook.KeyDown+=new KeyEventHandler(MyKeyDown);
            actHook.KeyPress+=new KeyPressEventHandler(MyKeyPress);
            actHook.KeyUp+=new KeyEventHandler(MyKeyUp);
        }

        public void MyKeyDown(object sender, MouseEventArgs e)
        {
            MessageBox.Show("CLICK");
        }

the problem is:
public UserActivityHook actHook;
The type or namespace name 'UserActivityHook' could not be found (are you missing a using directive or an assembly reference?)

That error message do I got.

Please help me out here :)

Felipe Ramos
posted  243 posts
since  Feb 28, 2008 
from 

 Re: Mouse background hook
  Posted on: 02 Sep 2010        0  
Maybe we are talking about different things, but I was under the impression that UserActivityHook was a class writtem to wrap Win32 calls using C# with P/Invoke. You can find a complete listing at koders.
webb webbhelp
posted  7 posts
since  Aug 30, 2010 
from 

 Re: Mouse background hook
  Posted on: 02 Sep 2010        0  
Hi!

First of all I want to thank you for replying, I really appreciate that :)

I got the class that I am supposed to use but now I got an error message :/


public void Start(bool InstallMouseHook, bool InstallKeyboardHook)
        {
            // install Mouse hook only if it is not installed and must be installed
            if (hMouseHook == 0 && InstallMouseHook)
            {
                // Create an instance of HookProc.
                MouseHookProcedure = new HookProc(MouseHookProc);
                //install hook
                hMouseHook = SetWindowsHookEx(
                    WH_MOUSE_LL,
                    MouseHookProcedure,
                    Marshal.GetHINSTANCE(
                        Assembly.GetExecutingAssembly().GetModules()[0]),
                    0);
                //If SetWindowsHookEx fails.
                if (hMouseHook == 0)
                {
                    //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
                    int errorCode = Marshal.GetLastWin32Error();
                    //do cleanup
                    Stop(true, false, false);
                    //Initializes and throws a new instance of the Win32Exception class with the specified error.
                    throw new Win32Exception(errorCode); //---------------------------------------------------------------------HERE IS THE PROBLEM
                }
            }

            // install Keyboard hook only if it is not installed and must be installed
            if (hKeyboardHook == 0 && InstallKeyboardHook)
            {
                // Create an instance of HookProc.
                KeyboardHookProcedure = new HookProc(KeyboardHookProc);
                //install hook
                hKeyboardHook = SetWindowsHookEx(
                    WH_KEYBOARD_LL,
                    KeyboardHookProcedure,
                    Marshal.GetHINSTANCE(
                    Assembly.GetExecutingAssembly().GetModules()[0]),
                    0);
                //If SetWindowsHookEx fails.
                if (hKeyboardHook == 0)
                {
                    //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
                    int errorCode = Marshal.GetLastWin32Error();
                    //do cleanup
                    Stop(false, true, false);
                    //Initializes and throws a new instance of the Win32Exception class with the specified error.
                    throw new Win32Exception(errorCode);
                }
            }
        }


I got a error message win32 exception i unhandled when I use this code:

        UserActivityHook actHook;
        private void playersDream_Load(object sender, EventArgs e)
        {
            actHook = new UserActivityHook(); // crate an instance with global hooks
            // hang on events
            actHook.OnMouseActivity += new MouseEventHandler(MouseMoved);
            actHook.KeyDown += new KeyEventHandler(MyKeyDown);
            actHook.KeyPress += new KeyPressEventHandler(MyKeyPress);
            actHook.KeyUp += new KeyEventHandler(MyKeyUp);
        }


        public void MouseMoved(object sender, MouseEventArgs e)
        {
            MessageBox.Show("1");
        }

        public void MyKeyDown(object sender, KeyEventArgs e)
        {
            MessageBox.Show("2");
        }

        public void MyKeyPress(object sender, KeyPressEventArgs e)
        {
            MessageBox.Show("3");
        }

        public void MyKeyUp(object sender, KeyEventArgs e)
        {
            MessageBox.Show("4");
        }

I include this:
using System;
using System.Windows.Forms;
using gma.System.Windows;

and the file "useractivityhook.cs" - class.

I have no idea what is wrong and I really hope you could help me.

I really appreciate your help and hope i got more help with this, thanks =)
Felipe Ramos
posted  243 posts
since  Feb 28, 2008 
from 

 Re: Mouse background hook
  Posted on: 02 Sep 2010        0  
I found the microsoft tutorial to set the hook for the mouse. It may be better for you to write this code and understand what is going on instead of using the UserActivityHook (couldn't debug it). I follow the tutorial and it worked.

webb webbhelp
posted  7 posts
since  Aug 30, 2010 
from 

 Re: Mouse background hook
  Posted on: 02 Sep 2010        0  
That one worked absolutely perfect!
I really appreciate your help, Thanks you so much :D
webb webbhelp
posted  7 posts
since  Aug 30, 2010 
from 

 Re: Mouse background hook
  Posted on: 02 Sep 2010        0  
I have a a few more question I would be happy if you could help me with :/

* This reacts when the mouse is moving, how can I decide a function to run when I CLICK?
Does this functions, works with keyboard events to?

I got a warning:

'System.AppDomain.GetCurrentThreadId()' is obsolete: 'AppDomain.GetCurrentThreadId has been deprecated because it does not provide a stable Id when managed threads are running on fibers (aka lightweight threads). To get a stable identifier for a managed thread, use the ManagedThreadId property on Thread.  http://go.microsoft.com/fwlink/?linkid=14202'

I am not really good at C# yet, and specially not with threads, can I fix this warning, do you got a idéa?

I would be very happy if you want to spend some more minutes to help me with this :)
Felipe Ramos
posted  243 posts
since  Feb 28, 2008 
from 

 Re: Mouse background hook
  Posted on: 02 Sep 2010        0  

I checked with MSDN and the alternative for GetCurrentThreadId is ManagedThreadId. You can get the code for the keyboard hook from http://blogs.msdn.com/b/toub/archive/2006/05/03/589423.aspx. The same guy posted a blog about setting the mouse hook (http://blogs.msdn.com/b/toub/archive/2006/05/03/589468.aspx). Hope you have better luck with those posts. Also remember to use 2.0 Framework or higher for the code listing.
webb webbhelp
posted  7 posts
since  Aug 30, 2010 
from 

 Re: Mouse background hook
  Posted on: 03 Sep 2010        0  
Really thank you for all help, the most works now!
I use the code: http://support.microsoft.com/default.aspx?scid=kb;en-us;318804
Because I thought it worked but it didn't work like I wanted it!
Now I can only click in the program window, it doesn't work if I click outside the window, nothing is happening, I did a messagebox if you click, but the messagebox just shows if you click in the program :/

I would be really happy if you could see what is wrong, I uploaded my source files.

Thank you, I really hope you will help me more, I really appreciate your help, it doesn't seems that somebody knows this except you =)
Felipe Ramos
posted  243 posts
since  Feb 28, 2008 
from 

 Re: Mouse background hook
  Posted on: 03 Sep 2010        0  
webb the attached project is from a developer name George Mamaladze found in CodeProject.com. The solution contains the code for all the hooks you want to setup. There are a couple of difference on how to set global or applicaiton hooks, but the biggest change is the WH_MOUSE = 7 to WH_MOUSE_LL = 14. Hope the code speeds your project and good luck.
webb webbhelp
posted  7 posts
since  Aug 30, 2010 
from 

 Re: Mouse background hook
  Posted on: 03 Sep 2010        0  
Thank you very much, I will test It right now, but now when your here I take the minute to ask:
I read somewhere that globalhooks didn't worked in C#, is that wrong? or have I missunderstood it?
If you got time and want you can explane the different with global hooks and low level hooks, if you don't want, just ignore :)
I am happy your helping :)
Felipe Ramos
posted  243 posts
since  Feb 28, 2008 
from 

 Re: Mouse background hook
  Posted on: 03 Sep 2010        0  
webb my understanding and I may be wrong is that local hooks refers to the hooks that work only for your application and global hooks work outside of it. For instance the issue you were having with the clicks not working outside of your form. What I did hear was that the global hooks didn't work in Vista or 7.
webb webbhelp
posted  7 posts
since  Aug 30, 2010 
from 

 Re: Mouse background hook
  Posted on: 03 Sep 2010        0  
Thanks thanks thanks :)

The program works perfect, exact how I wanted it ;P
But now I got another problem, I actually think it is the last :P

When the user click somewhere in the computer, I got this code to make 1 more click:
            //Call the imported function with the cursor's current position
            int X = Cursor.Position.X;
            int Y = Cursor.Position.Y;
            mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);

It works, it clicks BUT when I click on the left mousebutton, a function with  this code in, runs and make a click, and when this click the hook thinks that I am clicking, so I got into an infinity loop here ;P

I am not sure what I shall do to fix it, I tried to add a boolean variable that changed to true when I clicked on the mouse and then it went back to false when the program had clicked but it didn't worked.
I uploaded the files if it would be needed!

in: HookManager.Callbacks.cs , there is where the check if a mouse button has been press is, in there I call a function in the class: MouseEvents.cs, and that function is the function which simulate a click!

I would be very happy if you could spend a little bit more time on this, because I think and hope this is the last question.
I didn't wanted to ask but iI didn't succed to solve it by my self, I have tried for hours now :/

Thanks =)
       
Team Foundation Server Hosting
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
6 Months Free & No Setup Fees ASP.NET Hosting!
 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Advertise with us
Current Version: 5.2011.3.12
 © 1999 - 2012  Mindcracker LLC. All Rights Reserved