加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 23:56:43 所属栏目:大数据 来源:网络整理
导读:实现关机和重新启动 实例说明 在本实例中,我们将制作一个能重新启动和关闭计算机的应用程序。程序运行后,弹出如图86-1所示的界面,用户选择相应的选项后即可执行关机和重新启动操作。并将此次的选择保存下来。 图86-1 运行结果 技术要点 l 关闭和重新启动计
实现关机和重新启动

实例说明

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

图86-1 运行结果

技术要点

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读