개발언어/C#
[C#] WinAPI(Kernel32 dll) 사용하기
창용이랑
2020. 11. 3. 14:13
728x90
Kernel32.dll에서 GetSystemTime / SetSystemTime 호출해서 사용하기
C# / .NET 에서 Native DLL (Unmanaged DLL)에 있는 함수를 호출하는 P/Inovoke(Platform Invoke) 방식을 사용하여
C#에서 WinAPI를 호출하거나 C/C++로 작성된 Native DLL 함수를 호출한다.
1. DllImport 키워드를 사용해서 함수 호출하기
using System.Runtime.InteropServices;
namespace TEST.APIs
{
public static class Kernel32
{
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool GetSystemTime(ref SYSTEMTIME st);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool SetSystemTime(ref SYSTEMTIME st);
}
}
2. Struct SYSTEMTIME
using System.Runtime.InteropServices;
namespace TEST.APIs
{
[StructLayout(LayoutKind.Sequential)]
public struct SYSTEMTIME
{
public short Year;
public short Month;
public short DayOfWeek;
public short Day;
public short Hour;
public short Minute;
public short Second;
public short Milliseconds;
}
3. 호출해서 사용하기
//GetSystemTime
SYSTEMTIME getDate = new SYSTEMTIME();
GetSystemTime(ref getDate);
Console.Write("getSystemtime year: {0}", getDate.Year);
//SetSystemTime
public void SetSystemTimeFromDbServer()
{
using (var db = MasterContext.CreateDatabase())
{
var dbDate = db.ScalarQuery("SELECT GETDATE()").ExToDateTime(DateTime.Now).ToUniversalTime();
//
//
//
APIs.SYSTEMTIME setDate = new APIs.SYSTEMTIME();
setDate.Year = (short)dbDate.Year;
setDate.Month = (short)dbDate.Month;
setDate.Day = (short)dbDate.Day;
setDate.Hour = (short)dbDate.Hour;
setDate.Minute = (short)dbDate.Minute;
setDate.Second = (short)dbDate.Second;
//
//
//
APIs.Kernel32.SetSystemTime(ref setDate);
}
}