Não consigo fazer com que o SetSystemTime funcione no Windows Vista usando C # com interoperabilidade (P / Invoke)
Estou tendo dificuldades para fazer com que SetSystemTime funcione no meu código C #. SetSystemtime é uma função kernel32.dll. Estou usando P / invocar (interoperabilidade) para chamá-lo. SetSystemtime retorna false e o erro é "Parâmetro inválido". Publiquei o código abaixo. Sublinho que o GetSystemTime funciona bem. Eu testei isso no Vista e no Windows 7. Com base em algumas postagens de grupos de notícias que vi, desliguei o UAC. Não faz diferença. Eu fiz algumas pesquisas para esse problema. Encontrei este link:http://groups.google.com.tw/group/microsoft.public.dotnet.framework.interop/browse_thread/thread/805fa8603b00c267
onde o problema é relatado, mas nenhuma solução parece ser encontrada. Observe que o UAC também é mencionado, mas não tenho certeza se esse é o problema. Observe também que esse cavalheiro não recebe Win32Error real.
Alguém pode experimentar o meu código no XP?Alguém pode me dizer o que estou fazendo de errado e como corrigi-lo. Se a resposta for alterar de alguma forma as configurações de permissão programaticamente, eu precisaria de um exemplo. Eu teria pensado que desligar o UAC deveria cobrir isso.Não sou obrigado a usar essa maneira específica (SetSystemTime). Eu só estou tentando introduzir algum "desvio do relógio" para testar alguma coisa. Se houver outra maneira de fazê-lo, por favor me diga. Francamente, estou surpreso por precisar usar o Interop para alterar a hora do sistema. Eu teria pensado que existe um método .NET.Muito obrigado por qualquer ajuda ou idéias. Andrew
Código:
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);
}
}
}
}