[VB.NET]实现关机和重新启动

实现关机和重新启动

实例说明

在本实例中,我们将制作一个能重新启动和关闭计算机的应用程序。程序运行后,弹出如图86-1所示的界面,用户选择相应的选项后即可执行关机和重新启动操作。并将此次的选择保存下来。

图86-1 运行结果

<script type="text/javascript"> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>

技术要点

l 关闭和重新启动计算机

l 窗体的KeyPreview 属性

实现过程

■ 新建项目

打开Visual Studio.NET,选择"新建项目",在项目类型窗口中选择"Visual Basic项目",在模板窗口中选择"Windows应用程序",在名称域中输入"ControlComputer",然后选择保存路径。单击"确认"。

■ 添加控件

向当前窗体添加一个Label控件、一个PictureBox控件、两个Button按钮和三个RadioButton控件。

■ 设置属性

切换到属性栏,对窗体及控件设置属性,详细情况如表86-1所示。

注意:如果KeyPreview 属性被设置为True,窗体将先于该窗体上的控件接收此事件。可用 KeyPreview 属性来创建全局键盘处理例程。

表86-1 窗体及控件的属性值

窗体/控件 属性 值

Form1 BorderStyle 4-Fixed ToolWindow

KeyPreview True

Command1 Caption 是(&Y)

Picture1 Picture App.path & "/1.jpg"

其他控件 Caption 跟界面一致

■ 添加代码

Private Declare Function ExitWindowsEx Lib "user32" (ByVal uFlags As Integer, ByVal dwReserved As Integer) As Integer

Const EWX_FORCE As Short = 4

Const EWX_LOGOFF As Short = 0

Const EWX_REBOOT As Short = 2

Const EWX_SHUTDOWN As Short = 1

Dim retval As Integer

' 定义Esc按键

Const VK_ESCAPE As Short = &H1Bs

Private Sub Command1_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles Command1.Click

If Option1.Checked Then

' 注销当前用户

retval = ExitWindowsEx(EWX_FORCE, 0)

ElseIf Option2.Checked Then

' 关闭计算机

retval = ExitWindowsEx(EWX_SHUTDOWN, 0)

ElseIf Option3.Checked Then

' 重新启动

retval = ExitWindowsEx(EWX_REBOOT, 0)

End If

End Sub

Private Sub Command2_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles Command2.Click

Me.Close()

End Sub

' 按Esc键时,结束应用程序

Private Sub Form1_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress

Dim KeyAscii As Short = Asc(eventArgs.KeyChar)

If KeyAscii = VK_ESCAPE Then

Me.Close()

End If

If KeyAscii = 0 Then

eventArgs.Handled = True

End If

End Sub

■ 运行程序

单击菜单"调试|启动"或单击 图标运行程序。

小结

本实例通过使用ExitWindowEx()API函数来达到关机和重新启动的目的。在ExitWindowEx()函数中,参数uFlags指定要进行何种操作。在表86-2中列出了参数uFlags的值及其说明。

表86-2 参数uFlags的值及说明

常量名 值 说明

EWX_FORCE 4 终止所有进程,包括没有响应的进程,并注销Windows

EWX_REBOOT 2 重新启动系统

EWX_SHUTDOWN 1 关闭系统

EWX_LOGOFF 0 终止所有正在运行的进程,并注销Windows

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值