有時(shí)我們編寫(xiě)的程序需要進(jìn)行鎖屏和關(guān)屏操作,在網(wǎng)上搜索了一下,終于找到了可行的解決方案。全文如下:
最近找到了windows鎖屏API:LockWorkStation,并把之前的關(guān)屏API整合了一下,編寫(xiě)了一個(gè)可以選擇自動(dòng)鎖屏+關(guān)屏的程序。程序源代碼片段如下:
public Form1( bool aLock ) {
if (aLock) {
//鎖屏+關(guān)屏
LockWorkStation();
SendMessage( this.Handle, (uint)0x0112, (IntPtr)0xF170, (IntPtr)2 );
}
else {
//禁止鼠標(biāo)鍵盤(pán)動(dòng)作+關(guān)屏
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 );
}
//關(guān)屏
[DllImport( "user32.dll", CharSet = CharSet.Auto )]
static extern IntPtr SendMessage( IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam );
//禁止鼠標(biāo)鍵盤(pán)動(dòng)作
[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();
需要指出的是,在退出程序時(shí)要使用Environment.Exit( 0 );而非Application.Exit();否則會(huì)出錯(cuò)而提示類(lèi)似:“***遇到錯(cuò)誤,需要關(guān)閉”。
最后修改一下Main函數(shù)代碼:
static void Main(string[] args) {
//Application.EnableVisualStyles();
//Application.SetCompatibleTextRenderingDefault( false );
if (args == null || args.Length == 0) {
//禁止鼠標(biāo)鍵盤(pán)動(dòng)作+關(guān)屏
Application.Run( new Form1( false ) );
}
else {
//鎖屏+關(guān)屏
Application.Run( new Form1( true ) );
}
}
..
這樣,我們就可以實(shí)現(xiàn)鎖屏和關(guān)屏了。為了方便,你可以新建個(gè)快捷方式,加個(gè)參數(shù),即可鎖屏。
新聞熱點(diǎn)
疑難解答
圖片精選