I am working on setting Date and Time on Windows Embedded Standard 7 OS using C# .net.
I tried changing the system date using code in following link.
http://www.pinvoke.net/default.aspx/kernel32.setsystemtime
But I also saw that one should get the privileges to change the same. But I am receiving an error. here is the code to
Privileges.EnablePrivilege(SecurityEntity.SE_SYSTEMTIME_NAME);
if (SetSystemTime(ref st) == 0)
{
return 0;
}
return 1;
For getting the privaleges I used the code from the following link.
http://www.pinvoke.net/default.aspx/advapi32/AdjustTokenPrivileges.html C# Sample Code 2 (With full error handling):
I have question: Is it possible to change the Date and Time using PInvoke. If it is possible what are the change/Setting I should do at the OS.
And what are the other ways to change the date and time.
thank you
Edit:
[DllImport("kernel32.dll")]
extern static uint SetSystemTime(ref SYSTEMTIME lpSystemTime);
public int SetSystemDateTime(DateTime NewSystemDateTime)
{
SYSTEMTIME st = new SYSTEMTIME();
st.wYear = (ushort)NewSystemDateTime.Year;
st.wMonth = (ushort)NewSystemDateTime.Month;
st.wDay = (ushort)NewSystemDateTime.Day;
st.wHour = (ushort)NewSystemDateTime.Hour;
st.wMinute = (ushort)NewSystemDateTime.Minute;
st.wMilliseconds = (ushort)NewSystemDateTime.Millisecond;
Privileges.EnablePrivilege(SecurityEntity.SE_SYSTEMTIME_NAME);
if (SetSystemTime(ref st) == 0)
{
return 0;
}
return 1;
}
I finally found the solution. Code in the following link works fine for me: http://www.pinvoke.net/default.aspx/kernel32/SetLocalTime.html
Also following code I found in one of the posts in stackoverflow, helped me.
using System.Security.Principal;
bool IsUserAdministrator()
{
bool isAdmin;
try
{
WindowsIdentity user = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(user);
isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
}
catch (UnauthorizedAccessException ex)
{
isAdmin = false;
}
catch (Exception ex)
{
isAdmin = false;
}
return isAdmin;
}