Click here to Skip to main content
15,887,947 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'm using the following code:

C#
public partial class ThisAddIn
{
    private const int WH_KEYBOARD_LL = 13;
    private const int WM_KEYDOWN = 0x0100;

    private static IntPtr hookId = IntPtr.Zero;
    private delegate IntPtr HookProcedure(int nCode, IntPtr wParam, IntPtr lParam);
    private static HookProcedure procedure = HookCallback;

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr GetModuleHandle(string lpModuleName);

    [DllImport("user32.dll", SetLastError = true)]
    private static extern bool UnhookWindowsHookEx(IntPtr hhk);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr SetWindowsHookEx(int idHook, HookProcedure lpfn, IntPtr hMod, uint dwThreadId);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        hookId = SetHook(procedure);

    }

    private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
    {
        UnhookWindowsHookEx(hookId);
    }

    private static IntPtr SetHook(HookProcedure procedure)
    {
        using (Process process = Process.GetCurrentProcess())
        using (ProcessModule module = process.MainModule)
            return SetWindowsHookEx(WH_KEYBOARD_LL, procedure, GetModuleHandle(module.ModuleName), 0);
    }

    private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
        {
            int pointerCode = Marshal.ReadInt32(lParam);
            string pressedKey = ((Keys)pointerCode).ToString();

            //Do some sort of processing on key press
            var thread = new Thread(() =>
            {   MessageBox.Show(pressedKey);
                if (pressedKey.Equals("Space") || pressedKey.Equals("Tab"))
                    {
                        Word.Range rng = this.Application.ActiveDocument.Words.Last;
                        rng.Select();
                        rng.Copy();
                        String input = Clipboard.GetText(TextDataFormat.Text);
                    }
            });
            thread.Start();

        }
        return CallNextHookEx(hookId, nCode, wParam, lParam);
    }

    private void InternalStartup()
    {
        this.Startup += new System.EventHandler(ThisAddIn_Startup);
        this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
    }
}



I'm getting the following error for the line which is bold :

Error 1 Keyword 'this' is not valid in a static property, static method, or static field initializer.

Please advice
Posted
Updated 19-Oct-14 21:14pm
v2
Comments
BillWoodruff 20-Oct-14 8:01am    
There are several good articles on using GlobalHooks in .NET on CodeProject, including the "classic" one by George Mamaladze:

http://www.codeproject.com/Articles/7294/Processing-Global-Mouse-and-Keyboard-Hooks-in-C

I suggest you study those for ideas on using GlobalHook.

However, I (still) have no idea if these can be used to inter-operate with MS Word in .NET C# to do what you are trying to do here.
Tejas Shastri 20-Oct-14 11:17am    
Thanks Bill(Hope I can call you that).. Will check it out..
BillWoodruff 20-Oct-14 11:24am    
You're welcome. People who call me "Bill" I never worry about :)
Tejas Shastri 20-Oct-14 12:30pm    
Can you please check my code and see if there's a way to pass the string pressedkey from the method HookCallback to ThisAddIn_Startup.. thats the only problem..

Static methods (and properties, fields, etc) are not instance related - they are "global" to the containing class instead of being involved with a specific chunk of memory.

If you compare it to a car, "drive" is a "static method" for a car, because the instructions apply regardless of which car you are in. Whereas "fill with fuel" is dependant on the specific car - because it could require Petrol or Diesel and only by reference to the specific instance of a car your are trying to fill can you tell which.

So in a static method, you can't refer to instance properties - and that is what this is all about: accessing the instance of teh containing class.

Either remove the static keyword from the method declaration, or stop trying to use instance related items!
In this case, Application is not instance related, so you shouldn't need the this at all:
C#
Word.Range rng = Application.ActiveDocument.Words.Last;
should fix it.
 
Share this answer
 
Comments
Tejas Shastri 20-Oct-14 3:43am    
Didn't fix it..
OriginalGriff 20-Oct-14 4:05am    
I'm pretty sure it removed the error message "Keyword 'this' is not valid in a static property, static method, or static field initializer." - which is what you reported.

So what's the problem now?
Tejas Shastri 20-Oct-14 4:41am    
Error 1 An object reference is required for the non-static field, method, or property 'WordAddIn3.ThisAddIn.Application'
OriginalGriff 20-Oct-14 5:17am    
So you need an instance of the object in order to access it.
I assume that the callback means you can't have this as a non-static method?
In which case you only alternative is to have a static (possibly singleton) instance of the ThisAddIn class in order to access it inside the callback method.

Does that make sense?
Tejas Shastri 20-Oct-14 5:30am    
no.. it didn't :/
The message is fully informative. You cannot use "this" with static members. This is a reference to the object passed as an implicit parameter to a method or a property. In case of static members, such object simply does not exist; static members are referenced through the name of the type, without having any object of this type.

I would like to warn you against using Windows hook programming, when you have so weak knowledge of basics of OOP. Hook programming is one of the most difficult and error-prone techniques, because of multi-threading or multi-process issues, difficulty of debugging and other complications. Besides, you cannot use global hooks using .NET programming along; such hooks can be installed in a native (unmanaged) DLL.

—SA
 
Share this answer
 
v3
Comments
CPallini 20-Oct-14 3:05am    
5.
Sergey Alexandrovich Kryukov 20-Oct-14 10:07am    
Thank you, Carlo.
—SA
Abhijit Ghosh (Subho) 20-Oct-14 12:33pm    
vote of 5
Sergey Alexandrovich Kryukov 20-Oct-14 12:39pm    
Thank you, Abhijit.
—SA
this cannot find any object reference since your declaration is static. The keyword this basically refers to an instance of the class at runtime. In this case, there is none. Remove static will fix the error.
 
Share this answer
 
Comments
Tejas Shastri 20-Oct-14 3:47am    
gives another error.
Abhijit Ghosh (Subho) 20-Oct-14 3:52am    
Please share the error. Actually just removing the static keyword should give error if you have called the method directly form elsewhere. But tell us in detail what's wrong. And pay heed to what SA has mentioned above, even if it doesn't solve your problem.
Tejas Shastri 20-Oct-14 4:56am    
I'm sorry but I need to read the key event.. Is there another way to do it without using a hook? If there is one please let me know..
Sergey Alexandrovich Kryukov 20-Oct-14 10:08am    
There is no such concept as "read event". What do you mean?
—SA
Tejas Shastri 20-Oct-14 4:58am    
And I have called the method directly..
private static HookProcedure procedure = HookCallback;

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900