C#学习教程:我无法使用C#和Interop(P/Invoke)让SetSystemTime在WindowsVista中工作我很难让SetSystemTime在我的C#代码中工作。SetSystemtime是一个kernel32.dll函数。我正在使用P/invoke(interop)来调用它。SetSystemtime返回false,错误为“InvalidParameter”。我已经发布了下面的代码。我强调GetSystemTime工作正常。我已经在Vista和Windows7上对此进行了测试。根据一些新闻组帖子,我看到我关闭了UAC。没有什么不同。我已经在这个问题上做了一些搜索。我找到了这个链接:http://groups.google.com.tw/group/microsoft.public.dotnet.framework.interop/browse_thread/thread/805fa8603b00c267来报告问题,但似乎没有找到解决方案。请注意,还提到了UAC,但我不确定这是否是问题所在。另请注意,这位先生没有得到实际的Win32Error。有人可以在XP上试用我的代码吗?有人可以告诉我我做错了什么以及如何解决它。如果答案是以某种方式以编程方式更改权限设置,我需要一个示例。我原以为关闭UAC应该覆盖它。我不需要使用这种特殊方式(SetSystemTime)。我只是想为压力测试引入一些“时钟漂移”。如果有其他方法,请告诉我。坦率地说,我很惊讶我需要使用Interop来更改系统时间。我原以为有一种.NET方法可以做到这一点。非常感谢任何帮助或想法。安德鲁码:usingSystem;使用System.Collections.Generic;使用System.Linq;使用系统文本;使用System.Runtime.InteropServices;namespaceSystemTimeInteropTest{classProgram{#regionClockDriftSetup[StructLayout(LayoutKind.Sequential)]publicstructSystemTime{[MarshalAs(UnmanagedType.U2)]publicshortYear;[MarshalAs(UnmanagedType.U2)]publicshortMonth;[MarshalAs(UnmanagedType.U2)]publicshortDayOfWeek;[MarshalAs(UnmanagedType.U2)]publicshortDay;[MarshalAs(UnmanagedType.U2)]publicshortHour;[MarshalAs(UnmanagedType.U2)]publicshortMinute;[MarshalAs(UnmanagedType.U2)]publicshortSecond;[MarshalAs(UnmanagedType.U2)]publicshort毫秒;}[DllImport("kernel32.dll")]publicstaticexternvoidGetLocalTime(outSystemTimesystemTime);[DllImport("kernel32.dll")]publicstaticexternvoidGetSystemTime(outSystemTimesystemTime);[DllImport("kernel32.dll",SetLastError=true)]publicstaticexternboolSetSystem时间(参考系统时间系统时间);//[DllImport("kernel32.dll",SetLastError=true)]//publicstaticexternboolSetLocalTime(//refSystemTimesystemTime);[System.Runtime.InteropServices.DllImportAttribute("kernel32.dll",EntryPoint="SetLocalTime")][返回:System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)]publicstaticexternboolSetLocalTime([InAttribute()]refSystemTimelpSystemTime);#endregionClockDriftSetupstaticvoidMain(string[]args){try{SystemTimesysTime;获取系统时间(出系统时间);sysTime.Milliseconds+=(short)80;sysTime.Second+=(短)3000;boolbResult=SetSystemTime(refsysTime);如果(bResult==false)抛出新的System.ComponentModel.Win32Exception();}catch(Exceptionex){Console.WriteLine("漂移错误:"+ex.Message);}}}}有一种.Net方法来设置时间;它默认情况下在C#中不可使用如果将对Microsoft.VisualBasic的引用添加到项目中,则只需编写:Microsoft.VisualBasic.DateAndTime.TimeOfDay=DateTime.Now.AddSeconds(3000).AddMilliseconds(80);您不能只将3000添加到秒字段。您需要指定0到60之间的秒数。您需要调整秒、分钟、小时等字段,使它们都在有效范围内。编辑最简单的方法实际上是调用SystemTimeToFileTime,然后将numSeconds*10000添加到它返回的值,然后调用FileTimeToSystemTime转换回SystemTime。以上是C#学习教程:我无法使用C#和Interop(P/Invoke)使SetSystemTime在WindowsVista中工作。分享的全部内容,如果对大家有用,需要了解更多C#学习教程,还望大家多多关注—本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
