C#锁屏
在一些C#的Windows应用程序中,需要在用户暂时离开时对计算机进行锁屏,一种简单的方案思路。设置该计算机屏幕保护为“在恢复时使用密码保护”,在应用程序中调用系统的屏幕保护程序即可。
优点:实现简单实用。
缺点:1、用户计算机需要提前设置使用屏幕保护并设置为““在恢复时使用密码保护”模式。
2、计算机的用户必需为本机的系统用户设置有一个较安全的登录密码。 对于缺点1可考虑在应用程序启动中自动检测设置(实际上是对系统注册表的一些操作)。对于缺点2,我想在运行有关键任务的计算机是必需的,否则也不用进行锁屏操作了。
实现:建立启动窗体TEST.CS:
using System;
using System.Collections.Generic; using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices; namespace TTMISAdmin
{
public partial class TEST : Form
{
public TEST()
{
InitializeComponent();
}
[DllImport("user32.dll")]
public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
public const int WM_SYSCOMMAND = 0x0112;
public const int SC_SCREENSAVE = 0xF140;
private void button1_Click(object sender, EventArgs e)
{
//启动屏幕保护程序
SendMessage(this.Handle,WM_SYSCOMMAND,SC_SCREENSAVE,0);
}
}
}
2.用C#实现自动锁屏+关屏代码
0 M5 |/ i( r+ p* Z/ {0 L
+ A/ K6 M. U6 {8 E( |
如下代码片段:
1. public Form1( bool aLock ) {
2. if (aLock) {
1 R0 x- r0 x$ m. [: j" F
3. //锁屏+关屏
: S, ?9 u; i% T; Y
4. LockWorkStation();
8 o; j9 S. } Z
5. SendMessage( this.Handle, (uint)0x0112, (IntPtr)0xF170, (IntPtr)2 );
& a" d' h9 {2 ^1 k3 t) Z
6. }
* U4 X# }5 u5 v
7. else {
8. //禁止鼠标键盘动作+关屏
9. BlockInput( true );
10. System.Threading.Thread.Sleep( 10 );
11. SendMessage( this.Handle, (uint)0x0112, (IntPtr)0xF170, (IntPtr)2 );
12. BlockInput( false );
13. }
14. this.Close();
15. //Application.Exit();
16. Environment.Exit( 0 );
0 B% h0 ]8 E, f* G7 L, f. a9 x% m 17. }
18. //关屏
19. [DllImport( "user32.dll", CharSet = CharSet.Auto )] 20. static extern IntPtr SendMessage( IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr
lParam );
21. //禁止鼠标键盘动作
22. [return: MarshalAs( UnmanagedType.Bool )] 23. [DllImport( "user32.dll", CharSet = CharSet.Auto, ExactSpelling = true )]
- r$ z+ ^( d! m+ m* O5 ^
24. public static extern bool BlockInput( [In, MarshalAs( UnmanagedType.Bool )] bool
fBlockIt );
25. //锁屏
0 A1 G+ K5 k# Z6 h! o( D
26. [DllImport( "user32.dll" )]
27. public static extern bool LockWorkStation();
需要指出的是,在退出程序时使用Environment.Exit( 0 );而非Application.Exit();否则会出错
哦~~提示类似:“***遇到错误,需要关闭”。
( x6 ~ b4 {# w. B还有就是修改一下Main:
1. static void Main(string[] args) {
2. //Application.EnableVisualStyles();
8 Q- ]. p/ q. Q% V1 l5 K 3. //Application.SetCompatibleTextRenderingDefault( false );
! y" o6 W3 i4 t( m3 r" g; ~ 4. if (args == null || args.Length == 0) {
5. //禁止鼠标键盘动作+关屏
2 ~" D- e, h& e7 l! ~9 N 6. Application.Run( new Form1( false ) );
7. }
9 Y M" k2 g2 p9 `+ v4 p5 c9 ], F$ }' {
8. else {
+ o/ ]% C9 }' {9 i5 }1 p 9. //锁屏+关屏
10. Application.Run( new Form1( true ) );
11. }
. F; I4 I. X# W
12. }