【问题标题】:Changing system time dynamically win7动态更改系统时间win7
【发布时间】:2016-05-01 13:58:53
【问题描述】:
Sub change_the_time(ByVal NewDateTime As DateTime)
        '
        Dim NewDateTime2 As DateTime
        '
        NewDateTime2 = #5/1/2016 5:52:15 PM#    ' try setting the time to this
        '
        'set the system date and time to this date and time - throw an exception if it can't
        Try
            TimeOfDay = NewDateTime2
        Catch ex As Exception
            MessageBox.Show("Could not set time. " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop)
        End Try
End Sub

嗨。 新网站所以希望我遵守规则:-) 我的问题是如何成功更改系统时间?我在这个网站上找到的上述代码(以及我项目其他部分的大量信息 - 谢谢!)并且没有错误,但它总是抛出异常。我以管理员身份运行,我尝试更改 UAC,但仍然无法更改时间。我读到我需要设置 SE_SYSTEMTIME_NAME 权限,但我设置了这个权限,以便所有用户(即我)都有权限,但仍然没有。 MS 参考here 没有提供太多见解。我怀疑这是特权问题,但我似乎看不到如何设置我需要的东西。我需要做什么才能让我的应用程序将系统时间更改为某个值?

更多信息...还有另一个问题,但它是 c# 而不是 Vb,我尝试了类似于该代码的东西,如下所示。还是

Private Sub change_the_time2(ByRef NewDateTime As DateTime)
  Dim d As DateTime
  d = #6/10/2011#   ' try setting the date to this before using NewDateTime
  Dim worked As Boolean
  '
  Try
      worked = setlocaltime(d)
      MsgBox(" 1. Did it work " & worked)
  Catch ex As Exception
      MsgBox(" 2. Did it work " & worked)
  End Try
End Sub

<DllImport("kernel32.dll", setLastError:=True)> _
Private Shared Function setlocaltime(ByRef time As System.DateTime) As Boolean

End Function

【问题讨论】:

  • 有什么异常?
  • 您好 SuperPeanut,“无法设置时间。安全权限不足,无法设置系统时间”
  • 你应该不需要以管理员身份运行吗?

标签: vb.net


【解决方案1】:

这本质上是 cmets 中提到的 this question 的副本。但是为了澄清与 C# 相对的 VB.NET,根据该问题中的一个答案:

在 Windows Vista、7、8 操作系统上,这需要 UAC 提示符才能 获得必要的管理权限以成功执行 设置系统时间函数。

原因是调用进程需要 SE_SYSTEMTIME_NAME 权限。期待 SetSystemTime 函数 协调世界时 (UTC) 中的 SYSTEMTIME 结构。它不会 否则按需要工作。

取决于您在哪里/如何获得 您的 DateTime 值,最好安全使用 ToUniversalTime() 在设置相应值之前 SYSTEMTIME 结构体。

代码示例(针对 VB.NET 修改):

Dim tempDateTime As DateTime = GetDateTimeFromSomeService()
Dim dateTime As DateTime = tempDateTime.ToUniversalTime()

Dim st As SYSTEMTIME
'All of these must be short
st.wYear = dateTime.Year.ToInt16()
st.wMonth = dateTime.Month.ToInt16()
st.wDay = dateTime.Day.ToInt16()
st.wHour = dateTime.Hour.ToInt16()
st.wMinute = dateTime.Minute.ToInt16()
st.wSecond = dateTime.Second.ToInt16()

// invoke the SetSystemTime method now
SetSystemTime(ByRef st)

是的,您需要管理员权限。

【讨论】:

  • 谢谢!错误与代码无关,尽管感谢您提供上面的代码,因为它比我拥有的任何东西都更精确。我以管理员身份运行时工作的代码。我以为我 正在 以管理员身份运行代码,但 正确 检查显示我不是这样。再次感谢您。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-19
  • 2012-01-03
相关资源
最近更新 更多