2025-03-28 09:49:56 +08:00

72 lines
2.7 KiB
C#

using SuperMap.RealEstate.Launcher_WinForm;
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
namespace SuperMap.RealEstate.Launcher
{
public abstract class LocalTimeHelper
{
public static bool SetLocalTime(string value, double seconds = 5)
{
string _DateTimeString = System_Extend.ToDecrypt(value);
if (string.IsNullOrEmpty(_DateTimeString))
return true;
DateTime _DateTime = DateTime.Parse(_DateTimeString);
//测试10分钟误差
//_DateTime = DateTime.Now.AddMinutes(-10);
TimeSpan _TimeSpan = _DateTime - DateTime.Now;
//默认30秒误差
if (Math.Abs(_TimeSpan.TotalMinutes) > seconds)
{
SetLocalTime(_DateTime);
Thread.Sleep(200);
Application.DoEvents();
}
_TimeSpan = _DateTime - DateTime.Now;
if (Math.Abs(_TimeSpan.TotalMinutes) > seconds)
{
LoadingHelper.ForceExit();
MessageBox.Show("请确保本地时间与服务器时间的差异在3分钟之内。\r\n" +
"目前与服务器时间差异:" + Math.Abs(_TimeSpan.TotalMinutes).ToString("F0") + " 分钟。\r\n" +
"服务器时间:" + _DateTimeString ,"驿商科技", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
return true;
}
#region SetLocalTime
[DllImport("Kernel32.dll")]
private static extern bool SetLocalTime(ref SYSTEMTIME lpSystemTime);
[StructLayout(LayoutKind.Sequential)]
private struct SYSTEMTIME
{
public ushort wYear;
public ushort wMonth;
public ushort wDayOfWeek;
public ushort wDay;
public ushort wHour;
public ushort wMinute;
public ushort wSecond;
public ushort wMilliseconds;
}
private static void SetLocalTime(DateTime date)
{
SYSTEMTIME lpTime = new SYSTEMTIME();
lpTime.wYear = Convert.ToUInt16(date.Year);
lpTime.wMonth = Convert.ToUInt16(date.Month);
lpTime.wDayOfWeek = Convert.ToUInt16(date.DayOfWeek);
lpTime.wDay = Convert.ToUInt16(date.Day);
lpTime.wHour = Convert.ToUInt16(date.Hour);
lpTime.wMinute = Convert.ToUInt16(date.Minute);
lpTime.wSecond = Convert.ToUInt16(date.Second);
lpTime.wMilliseconds = Convert.ToUInt16(date.Millisecond);
SetLocalTime(ref lpTime);
}
#endregion
}
}