Last active
August 6, 2023 03:13
-
-
Save zombie110year/1560260f0b90c9691154688dadd28fbf to your computer and use it in GitHub Desktop.
立刻关闭显示器并锁屏,一个 Rust 调用 Windows API 的小工具。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //! ```toml | |
| //! # cargo.toml | |
| //! [package] | |
| //! name = "screenoff" | |
| //! version = "0.1.0" | |
| //! edition = "2021" | |
| //! description = "通过 Windows API 关闭电脑显示屏" | |
| //! # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | |
| //! | |
| //! [dependencies] | |
| //! windows = { version = "0.48.0", features = [ | |
| //! "Win32_Foundation", | |
| //! "Win32_System_Diagnostics_Debug", | |
| //! "Win32_System_Shutdown", | |
| //! "Win32_UI_WindowsAndMessaging", | |
| //! ] } | |
| //! ``` | |
| //! | |
| //! 参考链接: | |
| //! + <https://learn.microsoft.com/en-us/windows/win32/menurc/wm-syscommand> | |
| //! + <https://microsoft.github.io/windows-docs-rs/doc/windows/Win32/index.html> | |
| use windows::core::PWSTR; | |
| use windows::Win32::Foundation::{GetLastError, HWND, LPARAM, WPARAM}; | |
| use windows::Win32::System::Diagnostics::Debug::{FormatMessageW, FORMAT_MESSAGE_FROM_SYSTEM}; | |
| use windows::Win32::System::Shutdown::LockWorkStation; | |
| use windows::Win32::UI::WindowsAndMessaging::{PostMessageA, SC_MONITORPOWER, WM_SYSCOMMAND}; | |
| const HWND_BROADCAST: HWND = HWND(0xffff); | |
| #[allow(dead_code)] | |
| enum MonitorPower { | |
| On = -1isize, | |
| LowPower = 1isize, | |
| Off = 2isize, | |
| } | |
| fn main() { | |
| unsafe { | |
| let ok = PostMessageA( | |
| HWND_BROADCAST, | |
| WM_SYSCOMMAND, | |
| WPARAM(SC_MONITORPOWER as usize), | |
| LPARAM(MonitorPower::Off as isize), | |
| ); | |
| if !ok.as_bool() { | |
| panic_last_error(); | |
| } | |
| let ok = LockWorkStation(); | |
| if !ok.as_bool() { | |
| panic_last_error(); | |
| } | |
| } | |
| } | |
| unsafe fn panic_last_error() -> ! { | |
| let errorcode = GetLastError(); | |
| let mut errmsg = [0u16; 1024]; | |
| FormatMessageW( | |
| FORMAT_MESSAGE_FROM_SYSTEM, | |
| None, | |
| errorcode.0, | |
| 0, // 当前用户使用的语言 | |
| PWSTR(&mut errmsg as *mut u16), | |
| 1024, | |
| None, | |
| ); | |
| let errmsg = String::from_utf16_lossy(&errmsg); | |
| panic!("错误(0x{:x}): {}", errorcode.0, &errmsg); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment