Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

So I have 2 classes: Timers and KeyHook.

In the Timers class I have a public variable called lastInteraction of type DateTime.

The KeyHook class is responsible for listening to keyboard events. Currently it prints to the screen when a key is pressed.

I want the KeyHook event to update the lastInteraction variable with the current DateTime, is that possible? Even if I create the KeyHook instance within the timer class it doen't help.

How can I achieve such thing, I serached online but to the best of my knowledge a variable can't be shared across classes and passing the values around between classes won't work.


Some code snippets:

Program.cs

static void Main(string[] args)
{
    BeatW.Timers timer = new BeatW.Timers();
    timer.startTimers();

    KeyHook kh = new KeyHook();

    Console.ReadKey();
}

KeyHook.cs

public static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
    if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
    {
        int vkCode = Marshal.ReadInt32(lParam);
        Console.WriteLine((Keys)vkCode);
    }
    return CallNextHookEx(_hookID, nCode, wParam, lParam);
}

Timers.cs

class Timers
{
    public DateTime lastInteraction;
    ...
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
320 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you set a static class it is possible to do what you want to.

public static class Timers
{
    public static DateTime lastInteraction { get; set; }
    ...
}

And in the KeyHook class you can put values on it.

public static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
    if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
    {
        int vkCode = Marshal.ReadInt32(lParam);
        >>>>>Timers.lastInteraction = DateTime.Now;
        Console.WriteLine((Keys)vkCode);
    }
    return CallNextHookEx(_hookID, nCode, wParam, lParam);
}

And you can access the value of Timers.lastInteraction on all namespace range at runtime.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...