Implementation of Windows program automatic lock screen function

Source: Internet
Author: User

This question is from the Forum

Q: When I log on to the main interface and do not perform any operation within the specified time, the system will log out (just like the screen saver on the computer ).

A: Actually, it's very easy. Just refer to an API function: getlastinputinfo. The following is the reference code.

The demo program is minimized without any mouse or keyboard activity within 10 seconds. Then, shake the mouse to restore it.

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
Windowsapplication28

...
{


Public
 
Partial
 
Class
Form1: Form


...
{

[Structlayout (layoutkind. Sequential)]


Public
 
Struct
Lastinputinfo


...
{

[Financialas (unmanagedtype. U4)]


Public
 
Int
Cbsize;

[Financialas (unmanagedtype. U4)]


Public
 
Uint
Dwtime;

}



[Dllimport (
"
User32.dll
"
)]


Public
 
Static
 
Extern
 
Bool
Getlastinputinfo (
Ref
Lastinputinfo plii );





Public
 
Long
Getidletick ()


...
{

Lastinputinfo vlastinputinfo
=
 
New
Lastinputinfo ();

Vlastinputinfo. cbsize
=
Marshal. sizeof (vlastinputinfo );


If
(
!
Getlastinputinfo (
Ref
Vlastinputinfo ))
Return
 
0
;


Return
Environment. tickcount
-
(
Long
) Vlastinputinfo. dwtime;

}





Public
Form1 ()


...
{

Initializecomponent ();

}





Private
 
Void
Form1_load (
Object
Sender, eventargs E)


...
{


This
. Timer1.interval
=
 
2000
;


This
. Timer1.enabled
=
 
True
;


}




Private
 
Void
Timereffectick (
Object
Sender, eventargs E)


...
{


Long
I
=
Getidletick ();


This
. Text
=
 
String
. Format (
"
You haven't moved {0} ms, says jinjazz.
"
, I );


If
(I
>
 
10
 
*
 
1000
)


...
{


This
. Windowstate
=
Formwindowstate. minimized;

}




Else



...
{


This
. Windowstate
=
Formwindowstate. normal;

}



}





}



}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.