中以编程方式设置时间

中以编程方式设置时间

本文介绍了在 Windows 7 中以编程方式设置时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个应用程序从 Windows 2000(不要问)移植到 Windows 7,我需要复制允许用户从 GUI 设置时间的功能.以前这是通过使用命令提示符直接调用时间"来完成的,但在 Windows 7 中用户权限似乎有所改变.

经过一些研究,您似乎可以通过调用 kernel32.dll 方法 Win32SetSystemTime 来设置时间,但是会出现相同的权限问题.阅读 MSDN,我认为我需要启用 SE_SYSTEMTIME_NAME,但无论我尝试什么,我似乎都无法完成这项工作.

是否有人有一些经过测试的 Windows 7 示例代码以允许 API 调用 Win32SetSystemTime?

解决方案

不知道为什么它不适合你.以下代码将时间设置为今天下午 4:12 UTC.(为我工作)

公开课程序{公共结构系统时间{公共超短年;公共超短月;公共 ushort DayOfWeek;公共超短日;公共超短时间;公共超短分钟;public ushort 第二;公共超短毫秒;};[DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]public extern static bool Win32SetSystemTime(ref SystemTime st);公共静态无效主要(字符串[]参数){SystemTime st = 新的 SystemTime{年 = 2010,月 = 10,日 = 18,小时 = 16,分钟 = 12,DayOfWeek = 1};}}

根据docs:p>

调用进程必须具有 SE_SYSTEMTIME_NAME 权限.默认情况下禁用此权限.SetSystemTime 函数在更改系统时间之前启用 SE_SYSTEMTIME_NAME 权限,并在返回之前禁用该权限.有关详细信息,请参阅以特殊权限运行.

看来这应该不是问题.

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?

解决方案

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:

So seems like that shouldn't be an issue.

这篇关于在 Windows 7 中以编程方式设置时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 01:15