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
280 views
in Technique[技术] by (71.8m points)

c# - Setting the time programmatically in Windows 7

I'm porting an application from Windows 2000 (don't ask) to Windows 7 and I need to replicate functionality that allows the user to set the time from a GUI. Previously this had been done with a call directly to 'time' using the command prompt, but it appears the user permissions have changed somewhat in Windows 7.

Having done some research, it appears that you can set the time using a call to the kernel32.dll method Win32SetSystemTime, but the same permissions issue arises. Reading MSDN I think I need to enable SE_SYSTEMTIME_NAME, however no matter what I try I can't seem to make this work.

Does anyone have some tested example code for Windows 7 to allow an API call to Win32SetSystemTime?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Not sure why it's not working for you. The following code sets the time to today's date at 4:12 PM UTC. (Worked for me)

public class Program 
{
    public struct SystemTime
    {
        public ushort Year;
        public ushort Month;
        public ushort DayOfWeek;
        public ushort Day;
        public ushort Hour;
        public ushort Minute;
        public ushort Second;
        public ushort Millisecond;
    };

    [DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]
    public extern static bool Win32SetSystemTime(ref SystemTime st);

    public static void Main(string[] args)
    {
        SystemTime st = new SystemTime
        {
            Year = 2010, Month = 10, Day = 18, Hour = 16, Minute = 12, DayOfWeek = 1
        };
    }
}

According to the docs:

The calling process must have the SE_SYSTEMTIME_NAME privilege. This privilege is disabled by default. The SetSystemTime function enables the SE_SYSTEMTIME_NAME privilege before changing the system time and disables the privilege before returning. For more information, see Running with Special Privileges.

So seems like that shouldn't be an issue.


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

...