/// <summary> /// The create window. /// </summary> private void CreateWindow() { var instanceHandle = Kernel32Methods.GetModuleHandle(IntPtr.Zero); _windowProc = WindowProc; var wc = new WindowClassEx { Size = (uint)Marshal.SizeOf <WindowClassEx>(), ClassName = "chromelywindow", CursorHandle = User32Helpers.LoadCursor(IntPtr.Zero, SystemCursor.IDC_ARROW), IconHandle = GetIconHandle(), Styles = WindowClassStyles.CS_HREDRAW | WindowClassStyles.CS_VREDRAW, BackgroundBrushHandle = new IntPtr((int)StockObject.WHITE_BRUSH), WindowProc = _windowProc, InstanceHandle = instanceHandle }; var resReg = User32Methods.RegisterClassEx(ref wc); if (resReg == 0) { Log.Error("chromelywindow registration failed"); return; } var styles = GetWindowStyles(_hostConfig.HostPlacement.State); var placement = _hostConfig.HostPlacement; NativeMethods.RECT rect; rect.Left = placement.Left; rect.Top = placement.Top; rect.Right = placement.Left + placement.Width; rect.Bottom = placement.Top + placement.Height; NativeMethods.AdjustWindowRectEx(ref rect, styles.Item1, false, styles.Item2); var hwnd = User32Methods.CreateWindowEx( styles.Item2, wc.ClassName, _hostConfig.HostPlacement.Frameless ? string.Empty : _hostConfig.HostTitle, styles.Item1, rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top, IntPtr.Zero, IntPtr.Zero, instanceHandle, IntPtr.Zero); if (hwnd == IntPtr.Zero) { Log.Error("chromelywindow creation failed"); return; } User32Methods.ShowWindow(Handle, styles.Item3); User32Methods.UpdateWindow(Handle); }
private Cache() { this.ProcessHandle = Kernel32Methods.GetCurrentProcess(); this.AppIconHandle = User32Helpers.LoadIcon(IntPtr.Zero, SystemIcon.IDI_APPLICATION); this.ArrowCursorHandle = User32Helpers.LoadCursor(IntPtr.Zero, SystemCursor.IDC_ARROW); this.WindowClassExSize = (uint)Marshal.SizeOf <WindowClassEx>(); }
/// <summary> /// yields time slice of current thread to specified target threads /// </summary> /// <param name="threadYieldTarget">yield type</param> public static void To(YieldTarget threadYieldTarget) { switch (threadYieldTarget) { case YieldTarget.None: break; case YieldTarget.AnyThreadOnAnyProcessor: // reduce sleep to actually 1ms instead of system time slice with is around 15ms WinmmMethods.TimeBeginPeriod(1); Thread.Sleep(1); // undo WinmmMethods.TimeEndPeriod(1); break; case YieldTarget.SameOrHigherPriorityThreadOnAnyProcessor: Thread.Sleep(0); break; case YieldTarget.AnyThreadOnSameProcessor: Kernel32Methods.SwitchToThread(); break; default: throw new ArgumentOutOfRangeException(nameof(threadYieldTarget)); } }
protected override void OnTestCleanup() { Kernel32Methods.ResetDllDirectory(); Monitor.Exit(this.mutex); GC.Collect(2, GCCollectionMode.Forced, true); GC.WaitForPendingFinalizers(); }
protected override void OnTestInitialize() { Monitor.Enter(this.mutex); Kernel32Methods.SetDllDirectory("graphviz"); GC.Collect(2, GCCollectionMode.Forced, true); GC.WaitForPendingFinalizers(); }
private bool OpenFileHandle(Win32FileAccess desiredAccess) { handle = Kernel32Methods.CreateFile( devicePath, desiredAccess, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, (uint)Win32FileAttributes.Overlapped, IntPtr.Zero); return(handle.IsInvalid == false); }
public void Init(string title, int width, int height, bool vsync, bool fullscreen) { if (m_Info != null) { throw new InvalidOperationException("application already initialized"); } m_Info = new ApplicationInfo { Title = title, Width = width, Height = height, VSync = vsync, FullScreen = fullscreen }; IntPtr hInstance = Kernel32Methods.GetModuleHandle(IntPtr.Zero); m_WindowProc = WindowProc; var wc = new WindowClassEx { Size = (uint)Marshal.SizeOf <WindowClassEx>(), ClassName = "MainWindow", CursorHandle = User32Helpers.LoadCursor(IntPtr.Zero, SystemCursor.IDC_ARROW), IconHandle = User32Helpers.LoadIcon(IntPtr.Zero, SystemIcon.IDI_APPLICATION), Styles = WindowClassStyles.CS_HREDRAW | WindowClassStyles.CS_VREDRAW | WindowClassStyles.CS_OWNDC, BackgroundBrushHandle = new IntPtr((int)StockObject.WHITE_BRUSH), WindowProc = m_WindowProc, InstanceHandle = hInstance }; if (User32Methods.RegisterClassEx(ref wc) == 0) { throw new ExternalException("window registration failed"); } NetCoreEx.Geometry.Rectangle size = new NetCoreEx.Geometry.Rectangle(0, 0, width, height); User32Methods.AdjustWindowRectEx(ref size, WindowStyles.WS_OVERLAPPEDWINDOW | WindowStyles.WS_CLIPCHILDREN | WindowStyles.WS_CLIPSIBLINGS, false, WindowExStyles.WS_EX_APPWINDOW | WindowExStyles.WS_EX_WINDOWEDGE); m_hWnd = User32Methods.CreateWindowEx(WindowExStyles.WS_EX_APPWINDOW | WindowExStyles.WS_EX_WINDOWEDGE, wc.ClassName, title, WindowStyles.WS_OVERLAPPEDWINDOW | WindowStyles.WS_CLIPCHILDREN | WindowStyles.WS_CLIPSIBLINGS, (int)CreateWindowFlags.CW_USEDEFAULT, (int)CreateWindowFlags.CW_USEDEFAULT, size.Right + (-size.Left), size.Bottom + (-size.Top), IntPtr.Zero, IntPtr.Zero, hInstance, IntPtr.Zero); if (m_hWnd == IntPtr.Zero) { throw new ExternalException("window creation failed"); } User32Methods.ShowWindow(m_hWnd, ShowWindowCommands.SW_SHOWNORMAL); User32Methods.UpdateWindow(m_hWnd); Context.Instance.Init(m_hWnd, m_Info); Renderer.Instance.Init(); Script.LuaEngine.Instance.Init(); }
public void Kernel32_SetDllDirectory() { this.SkipTestOnLinux(); Kernel32Methods.ResetDllDirectory(); Kernel32Methods.SetDllDirectory("test"); Kernel32Methods.ResetDllDirectory(); }
static int Main(string[] args) { var instanceHandle = Kernel32Methods.GetModuleHandle(IntPtr.Zero); var wc = new WindowClassEx { Size = (uint)Marshal.SizeOf <WindowClassEx>(), ClassName = "MainWindow", CursorHandle = User32Helpers.LoadCursor(IntPtr.Zero, SystemCursor.IDC_ARROW), IconHandle = User32Helpers.LoadIcon(IntPtr.Zero, SystemIcon.IDI_APPLICATION), Styles = WindowClassStyles.CS_HREDRAW | WindowClassStyles.CS_VREDRAW, BackgroundBrushHandle = new IntPtr((int)StockObject.WHITE_BRUSH), WindowProc = WindowProc, InstanceHandle = instanceHandle }; var resReg = User32Methods.RegisterClassEx(ref wc); if (resReg == 0) { Console.Error.WriteLine("registration failed"); return(-1); } var hwnd = User32Methods.CreateWindowEx(WindowExStyles.WS_EX_APPWINDOW, wc.ClassName, "Hello", WindowStyles.WS_OVERLAPPEDWINDOW, (int)CreateWindowFlags.CW_USEDEFAULT, (int)CreateWindowFlags.CW_USEDEFAULT, (int)CreateWindowFlags.CW_USEDEFAULT, (int)CreateWindowFlags.CW_USEDEFAULT, IntPtr.Zero, IntPtr.Zero, instanceHandle, IntPtr.Zero); if (hwnd == IntPtr.Zero) { Console.Error.WriteLine("window creation failed"); return(-1); } User32Methods.ShowWindow(hwnd, ShowWindowCommands.SW_SHOWNORMAL); User32Methods.UpdateWindow(hwnd); Message msg; int res; while ((res = User32Methods.GetMessage(out msg, IntPtr.Zero, 0, 0)) != 0) { User32Methods.TranslateMessage(ref msg); User32Methods.DispatchMessage(ref msg); } return(res); }
/// <summary> /// The create window. /// </summary> private void CreateWindow() { var instanceHandle = Kernel32Methods.GetModuleHandle(IntPtr.Zero); var wc = new WindowClassEx { Size = (uint)Marshal.SizeOf <WindowClassEx>(), ClassName = "chromelywindow", CursorHandle = User32Helpers.LoadCursor(IntPtr.Zero, SystemCursor.IDC_ARROW), IconHandle = GetIconHandle(), Styles = WindowClassStyles.CS_HREDRAW | WindowClassStyles.CS_VREDRAW, BackgroundBrushHandle = new IntPtr((int)StockObject.WHITE_BRUSH), WindowProc = WindowProc, InstanceHandle = instanceHandle }; var resReg = User32Methods.RegisterClassEx(ref wc); if (resReg == 0) { Log.Error("chromelywindow registration failed"); return; } var styles = GetWindowStyles(mHostConfig.HostState); var hwnd = User32Methods.CreateWindowEx( styles.Item2, wc.ClassName, mHostConfig.HostTitle, styles.Item1, 0, 0, mHostConfig.HostWidth, mHostConfig.HostHeight, IntPtr.Zero, IntPtr.Zero, instanceHandle, IntPtr.Zero); if (hwnd == IntPtr.Zero) { Log.Error("chromelywindow creation failed"); return; } User32Methods.ShowWindow(Handle, styles.Item3); User32Methods.UpdateWindow(Handle); }
private void RegisterClass(ref WindowClassExBlittable classEx) { if (User32Methods.RegisterClassEx(ref classEx) == 0) { var errString = string.Empty; var err = Kernel32Methods.GetLastError(); // It may not always be the correct code. Since we aren't using // Marshal's last error. If the CLR runtime calls into the // system meanwhile that may be returned instead, at times. if (err != 0) { errString = "Possible error code: " + err; } throw new Exception("Failed to register class. " + errString); } }
private static string GetErrorMessage(int code) { uint FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; StringBuilder message = new StringBuilder(255); Kernel32Methods.FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM, IntPtr.Zero, (uint)code, 0, message, (uint)message.Capacity, IntPtr.Zero); LastError = message.ToString(); return(LastError); }
public static bool EnsureConsole() { if (Kernel32Methods.GetConsoleWindow() != IntPtr.Zero) { return(true); } if (Kernel32Methods.AllocConsole()) { return(false); } Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true }); Console.SetError(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true }); Console.SetIn(new StreamReader(Console.OpenStandardInput())); return(true); }
/// <summary> /// Initializes a new instance of the <see cref="HidStream"/> class. /// </summary> /// <param name="devicePath">The path of the associated device.</param> public HidStream(string devicePath) { this.devicePath = devicePath; // Create the file handler from the device path // Win10 requires shared access this.handle = Kernel32Methods.CreateFile( devicePath, Win32Api.Win32FileAccess.GenericRead | Win32FileAccess.GenericWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, Win32FileAttributes.Overlapped, IntPtr.Zero); //this.handle = Kernel32Methods.CreateFile( // devicePath, // Win32Api.Win32FileAccess.GenericRead | Win32FileAccess.GenericWrite, // FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, Win32FileAttributes.Overlapped, IntPtr.Zero); if (this.handle.IsInvalid) { // TODO: raise a better exception throw new Exception("Failed to create device file", new Win32Exception(Marshal.GetLastWin32Error())); } }
protected override void SetupInternal(Configurator config) { bool initSuccess = Glfw.Init(); if (!initSuccess) { Engine.Log.Error("Couldn't initialize glfw.", MessageSource.Glfw); return; } _errorCallback = ErrorCallback; Glfw.SetErrorCallback(_errorCallback); #if ANGLE LoadLibrary("libEGL"); LoadLibrary("libGLESv2"); Glfw.WindowHint(Glfw.Hint.ClientApi, Glfw.ClientApi.OpenGLES); Glfw.WindowHint(Glfw.Hint.ContextCreationApi, Glfw.ContextApi.EGL); Glfw.WindowHint(Glfw.Hint.ContextVersionMajor, 3); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && Kernel32Methods.GetModuleHandle("renderdoc.dll") != IntPtr.Zero) { Glfw.WindowHint(Glfw.Hint.ContextVersionMinor, 1); } #endif if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { // Macs need a very specific context to be requested. Glfw.WindowHint(Glfw.Hint.ContextVersionMajor, 3); Glfw.WindowHint(Glfw.Hint.ContextVersionMinor, 2); Glfw.WindowHint(Glfw.Hint.OpenglForwardCompat, true); Glfw.WindowHint(Glfw.Hint.OpenglProfile, Glfw.OpenGLProfile.Core); } else { // Version set by the angle ifdef shouldn't be overwritten. #if !ANGLE Glfw.WindowHint(Glfw.Hint.ContextVersionMajor, 3); Glfw.WindowHint(Glfw.Hint.ContextVersionMinor, 3); Glfw.WindowHint(Glfw.Hint.OpenglForwardCompat, true); Glfw.WindowHint(Glfw.Hint.OpenglProfile, Glfw.OpenGLProfile.Core); #endif } Glfw.Window?win = Glfw.CreateWindow((int)config.HostSize.X, (int)config.HostSize.Y, config.HostTitle); if (win == null || win.Value.Ptr == IntPtr.Zero) { Engine.Log.Error("Couldn't create window.", MessageSource.Glfw); return; } _win = win.Value; Glfw.SetWindowSizeLimits(_win, (int)config.RenderSize.X, (int)config.RenderSize.Y, -1, -1); _focusCallback = FocusCallback; Glfw.SetWindowFocusCallback(_win, _focusCallback); _resizeCallback = ResizeCallback; Glfw.SetFramebufferSizeCallback(_win, _resizeCallback); Context = new GlfwGraphicsContext(_win); Context.MakeCurrent(); _keyInputCallback = KeyInput; Glfw.SetKeyCallback(_win, _keyInputCallback); _mouseButtonFunc = MouseButtonKeyInput; Glfw.SetMouseButtonCallback(_win, _mouseButtonFunc); _mouseScrollFunc = MouseScrollInput; Glfw.SetScrollCallback(_win, _mouseScrollFunc); void TextInputRedirect(Glfw.Window _, uint codePoint) { UpdateTextInput((char)codePoint); } _textInputCallback = TextInputRedirect; Glfw.SetCharCallback(_win, _textInputCallback); Glfw.Monitor[] monitors = Glfw.GetMonitors(); for (var i = 0; i < monitors.Length; i++) { Glfw.GetMonitorPos(monitors[i], out int x, out int y); Glfw.VideoMode videoMode = Glfw.GetVideoMode(monitors[i]); var mon = new GlfwMonitor(new Vector2(x, y), new Vector2(videoMode.Width, videoMode.Height)); UpdateMonitor(mon, true, i == 0); } FocusChanged(true); Glfw.FocusWindow(_win); #if OpenAL Audio = OpenALAudioAdapter.TryCreate(this) ?? (AudioContext) new NullAudioContext(); #else Audio = new NullAudioContext(); #endif }
// Ввод данных логина с паролем от TWS счета public static void SendLoginAndPassword(IntPtr window, string login, string password, ILogger logger) { WindowInfo pwi = new WindowInfo(); User32Methods.GetWindowInfo(window, ref pwi); int x = pwi.WindowRect.Left + (pwi.WindowRect.Width * 50 / 100); int y = pwi.WindowRect.Top + (pwi.WindowRect.Height * 47 / 100); User32Methods.ShowCursor(true); if (!User32Methods.SetForegroundWindow(window)) { var err = Kernel32Methods.GetLastError(); logger.LogDebug("SetForegroundWindow error {0}", err); } ; if (!User32Methods.ShowWindow(window, ShowWindowCommands.SW_RESTORE)) { var err = Kernel32Methods.GetLastError(); logger.LogDebug("ShowWindow error {0}", err); } if (!User32Methods.SetCursorPos(x, y)) { var err = Kernel32Methods.GetLastError(); logger.LogDebug("SetCursorPos error {0}", err); } GenerateInput() .AddMouseClick(0, 0) .AddMouseClick(0, 0) .Send(TimeSpan.FromSeconds(1)); GenerateInput() .AddText(login) .Send(TimeSpan.FromSeconds(1)); x = pwi.WindowRect.Left + (pwi.WindowRect.Width * 50 / 100); y = pwi.WindowRect.Top + (pwi.WindowRect.Height * 54 / 100); User32Methods.SetForegroundWindow(window); User32Methods.ShowWindow(window, ShowWindowCommands.SW_RESTORE); User32Methods.SetCursorPos(x, y); GenerateInput() .AddMouseClick(0, 0) .AddMouseClick(0, 0) .Send(TimeSpan.FromSeconds(1)); GenerateInput() .AddText(password) .Send(TimeSpan.FromSeconds(1)); x = pwi.WindowRect.Left + (pwi.WindowRect.Width * 50 / 100); y = pwi.WindowRect.Top + (pwi.WindowRect.Height * 73 / 100); User32Methods.SetForegroundWindow(window); User32Methods.ShowWindow(window, ShowWindowCommands.SW_RESTORE); User32Methods.SetCursorPos(x, y); GenerateInput() .AddMouseClick(0, 0) .Send(TimeSpan.FromSeconds(0)); }
/// <summary> /// The create window. /// </summary> private void CreateWindow() { var instanceHandle = Kernel32Methods.GetModuleHandle(IntPtr.Zero); _windowProc = WindowProc; var wc = new WindowClassEx { Size = (uint)Marshal.SizeOf <WindowClassEx>(), ClassName = "chromelywindow", CursorHandle = User32Helpers.LoadCursor(IntPtr.Zero, SystemCursor.IDC_ARROW), IconHandle = GetIconHandle(), Styles = WindowClassStyles.CS_HREDRAW | WindowClassStyles.CS_VREDRAW, BackgroundBrushHandle = new IntPtr((int)StockObject.WHITE_BRUSH), WindowProc = _windowProc, InstanceHandle = instanceHandle }; var resReg = User32Methods.RegisterClassEx(ref wc); if (resReg == 0) { Log.Error("chromelywindow registration failed"); return; } var styles = GetWindowStyles(_hostConfig.HostPlacement.State); var placement = _hostConfig.HostPlacement; NativeMethods.RECT rect; rect.Left = placement.Left; rect.Top = placement.Top; rect.Right = placement.Left + placement.Width; rect.Bottom = placement.Top + placement.Height; NativeMethods.AdjustWindowRectEx(ref rect, styles.Item1, false, styles.Item2); var hwnd = User32Methods.CreateWindowEx( styles.Item2, wc.ClassName, _hostConfig.HostPlacement.Frameless ? string.Empty : _hostConfig.HostTitle, styles.Item1, rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top, IntPtr.Zero, IntPtr.Zero, instanceHandle, IntPtr.Zero); if (hwnd == IntPtr.Zero) { Log.Error("chromelywindow creation failed"); return; } if (_hostConfig.HostPlacement.KioskMode) { //// Set new window style and size. var windowHDC = User32Methods.GetDC(Handle); var fullscreenWidth = Gdi32Methods.GetDeviceCaps(windowHDC, (int)DeviceCapsParams.HORZRES); var fullscreenHeight = Gdi32Methods.GetDeviceCaps(windowHDC, (int)DeviceCapsParams.VERTRES); User32Methods.ReleaseDC(Handle, windowHDC); User32Methods.SetWindowLongPtr(Handle, (int)WindowLongFlags.GWL_STYLE, (IntPtr)styles.Item1); User32Methods.SetWindowLongPtr(Handle, (int)WindowLongFlags.GWL_EXSTYLE, (IntPtr)styles.Item2); User32Methods.SetWindowPos(Handle, (IntPtr)HwndZOrder.HWND_TOP, 0, 0, fullscreenWidth, fullscreenHeight, WindowPositionFlags.SWP_NOZORDER | WindowPositionFlags.SWP_FRAMECHANGED); User32Methods.ShowWindow(Handle, ShowWindowCommands.SW_MAXIMIZE); try { this._hookID = NativeMethods.SetHook(_hookCallback); } catch { DetachKeyboardHook(); } } else { User32Methods.ShowWindow(Handle, styles.Item3); } User32Methods.UpdateWindow(Handle); User32Methods.RegisterHotKey(IntPtr.Zero, 1, KeyModifierFlags.MOD_CONTROL, VirtualKey.L); }
public static IDENTIFY_DEVICE_DATA?IdentifyDefice(string deviceName) { ATA_PASS_THROUGH_EX aptx = new ATA_PASS_THROUGH_EX(); ATADeviceQuiry adqry = new ATADeviceQuiry(); IDENTIFY_DEVICE_DATA idd = new IDENTIFY_DEVICE_DATA(); adqry.reqDataBuf = new byte[512]; adqry.header.Length = (ushort)Marshal.SizeOf(aptx); adqry.header.AtaFlags = ATA_FLAGS_DATA_IN; adqry.header.DataTransferLength = (ushort)adqry.reqDataBuf.Length; //512 adqry.header.DataBufferOffset = Marshal.OffsetOf(typeof(ATADeviceQuiry), "reqDataBuf"); adqry.header.TimeOutValue = 1; adqry.header.PreviousTaskFile = new IDEREGS(); adqry.header.CurrentTaskFile = new IDEREGS(); adqry.header.CurrentTaskFile.bCommandReg = WIN_IDENTIFYDEVICE; uint IOCTL_ATA_PASS_THROUGH = CTL_CODE( IOCTL_SCSI_BASE, 0x040b, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); SafeFileHandle driveHandle = Kernel32Methods.CreateFileW( lpFileName: deviceName, dwDesiredAccess: Kernel32Methods.GENERIC_READ | Kernel32Methods.GENERIC_WRITE, // Administrative privilege is required dwShareMode: Kernel32Methods.FILE_SHARE_READ | Kernel32Methods.FILE_SHARE_WRITE, lpSecurityAttributes: IntPtr.Zero, dwCreationDisposition: Kernel32Methods.OPEN_EXISTING, dwFlagsAndAttributes: Kernel32Methods.FILE_ATTRIBUTE_NORMAL, hTemplateFile: IntPtr.Zero); if (driveHandle == null || driveHandle.IsInvalid) { #if DEBUG string message = GetErrorMessage(Marshal.GetLastWin32Error()); Console.WriteLine($"CreateFile (IdentifyDevice) with disk {deviceName} failed. Error: " + message); #endif driveHandle?.Close(); return(null); } uint returnBytesCount; bool result = Kernel32Methods.DeviceIoControl( hDevice: driveHandle, dwIoControlCode: IOCTL_ATA_PASS_THROUGH, lpInBuffer: ref adqry, nInBufferSize: (uint)Marshal.SizeOf(adqry), lpOutBuffer: ref adqry, nOutBufferSize: (uint)Marshal.SizeOf(adqry), lpBytesReturned: out returnBytesCount, lpOverlapped: IntPtr.Zero); driveHandle.Close(); if (result == false) { #if DEBUG string message = GetErrorMessage(Marshal.GetLastWin32Error()); Console.WriteLine($"DeviceIoControl (IdentifyDevice) with disk {deviceName} failed. Error: " + message); #endif return(null); } // Raw memory copy of reqDataBuf byte array to IDENTIFY_DEVICE struct IntPtr tempPtr = Marshal.AllocHGlobal(Marshal.SizeOf(idd)); Marshal.Copy(adqry.reqDataBuf, 0, tempPtr, adqry.reqDataBuf.Length); idd = (IDENTIFY_DEVICE_DATA)Marshal.PtrToStructure(tempPtr, idd.GetType()); Marshal.FreeHGlobal(tempPtr); return(idd); }
/// <summary> /// Initializes a new instance of the <see cref="WindowsOperatingSystem"/> class. /// </summary> public WindowsOperatingSystem() { Kernel32Methods.SetConsoleCtrlHandler(this.OnConsoleCtrlEvent, true); }
public static bool SetAPM(string driveName, byte apmVal) { ATA_PASS_THROUGH_EX aptx = new ATA_PASS_THROUGH_EX(); ATADeviceQuiry adq = new ATADeviceQuiry(); adq.reqDataBuf = new byte[512]; aptx.Length = (ushort)Marshal.SizeOf(aptx);; aptx.AtaFlags = ATA_FLAGS_DATA_IN; aptx.DataTransferLength = (ushort)adq.reqDataBuf.Length; //512; aptx.TimeOutValue = 1; aptx.DataBufferOffset = Marshal.OffsetOf(typeof(ATADeviceQuiry), "reqDataBuf"); aptx.PreviousTaskFile = new IDEREGS(); aptx.CurrentTaskFile = new IDEREGS(); aptx.CurrentTaskFile.bCommandReg = SET_FEATURES; switch (apmVal) { case 0: { throw new ArgumentException("APM value cannot be 0"); } // Disable APM case DISABLE_APM_VALUE: { aptx.CurrentTaskFile.bFeaturesReg = SETFEATURES_DIS_APM; break; } // Set APM to value default: { aptx.CurrentTaskFile.bFeaturesReg = SETFEATURES_EN_APM; aptx.CurrentTaskFile.bSectorCountReg = apmVal; break; } } adq.header = aptx; uint IOCTL_ATA_PASS_THROUGH = CTL_CODE( IOCTL_SCSI_BASE, 0x040b, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); SafeFileHandle driveHandle = Kernel32Methods.CreateFileW( lpFileName: driveName, dwDesiredAccess: Kernel32Methods.GENERIC_READ | Kernel32Methods.GENERIC_WRITE, // Administrative privilege is required dwShareMode: Kernel32Methods.FILE_SHARE_READ | Kernel32Methods.FILE_SHARE_WRITE, lpSecurityAttributes: IntPtr.Zero, dwCreationDisposition: Kernel32Methods.OPEN_EXISTING, dwFlagsAndAttributes: Kernel32Methods.FILE_ATTRIBUTE_NORMAL, hTemplateFile: IntPtr.Zero); if (driveHandle == null || driveHandle.IsInvalid) { #if DEBUG string message = GetErrorMessage(Marshal.GetLastWin32Error()); Console.WriteLine($"CreateFile (APMControl) with disk {driveName} failed. Error: " + message); #endif driveHandle?.Close(); return(false); } uint returnBytesCount; bool result = Kernel32Methods.DeviceIoControl( hDevice: driveHandle, dwIoControlCode: IOCTL_ATA_PASS_THROUGH, lpInBuffer: ref adq, nInBufferSize: (uint)Marshal.SizeOf(adq), lpOutBuffer: ref adq, nOutBufferSize: (uint)Marshal.SizeOf(adq), lpBytesReturned: out returnBytesCount, lpOverlapped: IntPtr.Zero); driveHandle.Close(); if (result == false) { #if DEBUG string message = GetErrorMessage(Marshal.GetLastWin32Error()); Console.WriteLine($"DeviceIoControl (APMControl) with disk {driveName} failed. Error: " + message); #endif return(false); } return(result); }