C#コードでSetSystemTimeを機能させるのに苦労しています。SetSystemtimeはkernel32.dll関数です。P / invoke(相互運用)を使用して呼び出しています。SetSystemtimeはfalseを返し、エラーは「無効なパラメーター」です。以下のコードを投稿しました。GetSystemTimeは問題なく機能することを強調します。これをVistaとWindows7でテストしました。いくつかのニュースグループの投稿に基づいて、UACをオフにしました。変わりはない。私はこの問題を探しました。私はこのリンクを見つけました:http: //groups.google.com.tw/group/microsoft.public.dotnet.framework.interop/browse_thread/thread/805fa8603b00c267
問題は報告されていますが、解決策が見つからないようです。UACについても言及されていますが、これが問題かどうかはわかりません。また、この紳士は実際のWin32Errorを取得しないことに注意してください。
- 誰かが私のコードをXPで試すことができますか?
- 誰かが私が間違っていることとそれを修正する方法を教えてもらえますか?どういうわけかプログラムで権限設定を変更することが答えである場合は、例が必要です。ただし、UACをオフにすることでそれをカバーできると思いました。
- この特定の方法(SetSystemTime)を使用する必要はありません。何かをストレステストするために、「クロックドリフト」を導入しようとしています。別の方法があれば教えてください。率直に言って、システム時間を変更するために相互運用機能を使用する必要があることに驚いています。.NETメソッドがあると思いました。
助けやアイデアをありがとうございました。アンドリュー
コード:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace SystemTimeInteropTest
{
class Program
{
#region ClockDriftSetup
[StructLayout(LayoutKind.Sequential)]
public struct SystemTime
{
[MarshalAs(UnmanagedType.U2)]
public short Year;
[MarshalAs(UnmanagedType.U2)]
public short Month;
[MarshalAs(UnmanagedType.U2)]
public short DayOfWeek;
[MarshalAs(UnmanagedType.U2)]
public short Day;
[MarshalAs(UnmanagedType.U2)]
public short Hour;
[MarshalAs(UnmanagedType.U2)]
public short Minute;
[MarshalAs(UnmanagedType.U2)]
public short Second;
[MarshalAs(UnmanagedType.U2)]
public short Milliseconds;
}
[DllImport("kernel32.dll")]
public static extern void GetLocalTime(
out SystemTime systemTime);
[DllImport("kernel32.dll")]
public static extern void GetSystemTime(
out SystemTime systemTime);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool SetSystemTime(
ref SystemTime systemTime);
//[DllImport("kernel32.dll", SetLastError = true)]
//public static extern bool SetLocalTime(
//ref SystemTime systemTime);
[System.Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint = "SetLocalTime")]
[return: System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)]
public static extern bool SetLocalTime([InAttribute()] ref SystemTime lpSystemTime);
#endregion ClockDriftSetup
static void Main(string[] args)
{
try
{
SystemTime sysTime;
GetSystemTime(out sysTime);
sysTime.Milliseconds += (short)80;
sysTime.Second += (short)3000;
bool bResult = SetSystemTime(ref sysTime);
if (bResult == false)
throw new System.ComponentModel.Win32Exception();
}
catch (Exception ex)
{
Console.WriteLine("Drift Error: " + ex.Message);
}
}
}
}