Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

class - C# share or modify variables between classes

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...