2016-05-01 87 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身份運行時的代碼。我認爲我*是*以管理員身份運行代碼,但* * * * *表示否則會顯示我。再次感謝你。 –