-4

When I try to compile the below code, I get this one error:

An object reference is required for the non-static field, method, or property "Program._timer"

I understand from someone else in this thread I can't create the variable like that in my static Main() but I'm not sure how I should change it to get the functionality I'm trying to achieve.

I tried using this code to create the timer but that is how I got stuck in this error. How do you add a timer to a C# console application

using System;
using System.Xml.Linq;
using Microsoft.Win32;
using static Microsoft.Win32.SystemEvents;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Diagnostics.Metrics;
using System.Timers;
using System.Threading;

namespace CSharpTutorials
{
    class Program
    {
        private System.Threading.Timer _timer = null;
        public static void Main()
        {
            DateTime lastLogin, lastLock;
            string bossEmail;

            XDocument doc = XDocument.Load("properties.xml");
            XElement lastLockElement = doc.Descendants("lastLock").FirstOrDefault();
            //lastLockElement.FirstAttribute.Value
            XElement lastLoginElement = doc.Descendants("lastLogin").FirstOrDefault();
            //lastLoginElement.FirstAttribute.Value
            SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
           
            
            
            var mre = new ManualResetEvent(false);
            Console.CancelKeyPress += delegate (object sender, ConsoleCancelEventArgs e)
            {
                mre.Set();
            };
            mre.WaitOne();



            // Create a Timer object that knows to call our TimerCallback
            // method once every 2000 milliseconds.
            _timer = new System.Threading.Timer(TimerCallback, null, 0, 2000);


            
            

        }
        private static void TimerCallback(Object o)
        {
            // Display the date/time when this method got called.
            Console.WriteLine("In TimerCallback: " + DateTime.Now);
        }
        public static string GetTimestamp(DateTime value)
        {
            return value.ToString("yyyy/MM/dd HH:mm:ss");
        }
        static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
        {
            string timeStamp = GetTimestamp(DateTime.Now);
            // Load the XML file
            XDocument doc = XDocument.Load("prefrences.xml");

           

            switch (e.Reason)
            {
                case SessionSwitchReason.SessionLogon:
                    //Logon
                    //RecordLog(timeStamp + ": User logged into the session.");
                    XElement logonElement = doc.Descendants("lastLogin").FirstOrDefault();
                    if (logonElement != null)
                    {
                        // Modify the element's attributes or values with variables
                        logonElement.SetAttributeValue("lastLogin", DateTime.Now);
                        doc.Save("properties.xml");
                    }
                    break;
                case SessionSwitchReason.SessionLogoff:
                    //Logoff
                    //RecordLog(timeStamp + ": User logged off the session.");
                    break;
                case SessionSwitchReason.RemoteConnect:
                    //Remote Connect
                    //RecordLog(timeStamp + ": User remote connected.");
                    break;
                case SessionSwitchReason.RemoteDisconnect:
                    //Remote Disconnect
                    //RecordLog(timeStamp + ": User remote disconnected.");
                    break;
                case SessionSwitchReason.SessionLock:
                    //lockQ
                    //RecordLog(timeStamp + ": User locked the computer.");
                    // Find the element you want to modify
                    XElement lockElement = doc.Descendants("lastLock").FirstOrDefault();
                    if (lockElement != null)
                    {
                        // Modify the element's attributes or values with variables
                        lockElement.SetAttributeValue("lastLock", DateTime.Now);
                        doc.Save("properties.xml");
                    }
                    break;
                case SessionSwitchReason.SessionUnlock:
                    //Unlock
                    //RecordLog(timeStamp + ": User unlocked the computer.");
                    break;
                default:
                    break;
            }
        }
        //private static void RecordLog(string message)
        //{
        // Add code to record the event in a log file or database
        // For example, you can write the message to a log file:
        //using (StreamWriter writer = File.AppendText("log.txt"))
        //{
        //writer.WriteLine(message);
        //}
        //}
    }
}

Zac Borders
  • 137
  • 1
  • 3
  • 12
  • 5
    The errors are pretty clear. *Read them*. For example, you're trying to use the non-static field `_timer` in the static method `Main`. You can't do that. You're trying to use `SystemEvents_SessionSwitch` in a *different* file called `ProgramHelpers.cs`. I bet that file contains a `static void Main` as well – Panagiotis Kanavos Feb 15 '23 at 16:17
  • 1
    Sorry if the errors aren't as clear to me as they are you. I appreciate your clarification. I'm not sure where ProgramHelper.cs is from but I'll be getting rid of it. Thank you so much! – Zac Borders Feb 15 '23 at 16:26
  • Can you help me with the code needed to fix _Timer? I've updated the question to clarify. – Zac Borders Feb 15 '23 at 16:41
  • As all of your code only is contained in `static` methods, the easiest fix would be,making also the `_timer` a static. Ie `private static System.Threading.Timer _timer = null` ... – derpirscher Feb 15 '23 at 16:45
  • Here is your answer -- `An **object reference** is required for the **non-static field**, method, or property` – T.S. Feb 15 '23 at 16:46

1 Answers1

3

To access instance field initialize new instance of Program class:

var p = new Program();
p._timer = new System.Threading.Timer(TimerCallback, null, 0, 2000);

or make field static:

private static System.Threading.Timer _timer;

public static void Main()
{
    ...
    _timer = new System.Threading.Timer(TimerCallback, null, 0, 2000);
    ...
}
Arvis
  • 8,273
  • 5
  • 33
  • 46