有時我們編寫的程序需要進行鎖屏和關屏操作,在網上搜索了一下,終于找到了可行的解決方案。全文如下:
最近找到了windows鎖屏API:LockWorkStation,并把之前的關屏API整合了一下,編寫了一個可以選擇自動鎖屏+關屏的程序。程序源代碼片段如下:
public Form1( bool aLock ) {
if (aLock) {
//鎖屏+關屏
LockWorkStation();
SendMessage( this.Handle, (uint)0x0112, (IntPtr)0xF170, (IntPtr)2 );
}
else {
//禁止鼠標鍵盤動作+關屏
BlockInput( true );
System.Threading.Thread.Sleep( 10 );
SendMessage( this.Handle, (uint)0x0112, (IntPtr)0xF170, (IntPtr)2 );
BlockInput( false );
}
this.Close();
//Application.Exit();
Environment.Exit( 0 );
}
//關屏
[DllImport( "user32.dll", CharSet = CharSet.Auto )]
static extern IntPtr SendMessage( IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam );
//禁止鼠標鍵盤動作
[return: MarshalAs( UnmanagedType.Bool )]
[DllImport( "user32.dll", CharSet = CharSet.Auto, ExactSpelling = true )]
public static extern bool BlockInput( [In, MarshalAs( UnmanagedType.Bool )] bool fBlockIt );
//鎖屏
[DllImport( "user32.dll" )]
public static extern bool LockWorkStation();
需要指出的是,在退出程序時要使用Environment.Exit( 0 );而非Application.Exit();否則會出錯而提示類似:“***遇到錯誤,需要關閉”。
最后修改一下Main函數代碼:
static void Main(string[] args) {
//Application.EnableVisualStyles();
//Application.SetCompatibleTextRenderingDefault( false );
if (args == null || args.Length == 0) {
//禁止鼠標鍵盤動作+關屏
Application.Run( new Form1( false ) );
}
else {
//鎖屏+關屏
Application.Run( new Form1( true ) );
}
}
..
這樣,我們就可以實現鎖屏和關屏了。為了方便,你可以新建個快捷方式,加個參數,即可鎖屏。
新聞熱點
疑難解答
圖片精選