我正在使用C#.net在Windows Embedded Standard 7 OS上设置日期和时间。
我尝试使用以下链接中的代码更改系统日期。
http://www.pinvoke.net/default.aspx/kernel32.setsystemtime
但我也看到,应该获得更改相同内容的特权。但是我收到一个错误。这是代码
Privileges.EnablePrivilege(SecurityEntity.SE_SYSTEMTIME_NAME);
if (SetSystemTime(ref st) == 0)
{
return 0;
}
return 1;
为了获得特权,我使用了以下链接中的代码。
http://www.pinvoke.net/default.aspx/advapi32/AdjustTokenPrivileges.html C#示例代码2(具有完整的错误处理):
我有一个问题:是否可以使用PInvoke更改日期和时间。如果可能的话,我应该在OS上进行哪些更改/设置。
还有其他更改日期和时间的方法。
谢谢你
编辑:
[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;
}
我终于找到了解决方案。以下链接中的代码对我来说效果很好:http : //www.pinvoke.net/default.aspx/kernel32/SetLocalTime.html
同样遵循我在stackoverflow的其中一篇文章中找到的代码,对我有所帮助。
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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句