2016-05-01 89 views
2
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没有提供很多见解。我怀疑这是一个特权问题,但我似乎无法看到如何设置我所需要的。我需要做什么才能让我的应用程序将系统时间更改为某个值?动态更改系统时间win7

更多信息...还有一个问题沿着同样的路线,但它是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 
+0

什么是例外? –

+0

您好SuperPeanut,“无法设置时间。安全权限不足以设置系统时间” –

+0

可能重复[以编程方式更改系统日期](http://stackoverflow.com/questions/650849/change-system-date-programmatically) –

回答

1

这实质上是this question的副本,正如评论中提到的。但澄清VB.NET作为oposed到C#,每在这个问题的答案之一:

在Windows Vista,7,8操作系统,这将需要为了一个UAC提示,以 获得必要的管理权限以成功执行SetSystemTime函数 。

原因是调用进程需要 SE_SYSTEMTIME_NAME权限。 SetSystemTime函数期望在协调通用时间(UTC)中有一个SYSTEMTIME结构 。它不会 按需要工作,否则。

不同的地方/你是如何让你的 DateTime值,它可能是最好的发挥它的安全,并在 SYSTEMTIME结构设置相应的值之前使用 ToUniversalTime()。

代码示例(修改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) 

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

+0

谢谢!错误不在代码中,尽管感谢上面的代码,因为它比我的任何东西都更精确。我以admin身份运行时的代码。我认为我*是*以管理员身份运行代码,但* * * * *表示否则会显示我。再次感谢你。 –