VB.net 定时关机程序(WPF)

程序预览图

Xaml(界面代码)

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit" x:Class="MainWindow"
    Title="定时关机" Height="214.474" Width="332.895" ResizeMode="NoResize">
    <Grid>
        <xctk:DateTimePicker x:Name="EndTimes" Margin="82,43,26,117"/>
        <Label Content="关机时间:" Margin="10,43,248,117"/>
        <Button Content="启动" Margin="251,153,26,10" Click="Button_Click"/>
        <Label Content="剩余时间:" Margin="10,115,248,45"/>
        <TextBlock x:Name="TimeAdds" Margin="82,121,116,45" TextWrapping="Wrap"/>
        <Label Content="执行操作::" Margin="10,80,248,80"/>
        <ComboBox x:Name="TimeMode" Margin="82,80,26,80" SelectedIndex="0">
            <ComboBoxItem Content="关机"/>
            <ComboBoxItem Content="重启"/>
            <ComboBoxItem Content="注销"/>
        </ComboBox>
    </Grid>
</Window>

Vb.net代码

Imports System.Runtime.InteropServices
Imports Microsoft.VisualBasic
Imports System.Windows.Threading
Imports System.Text

Class MainWindow
    Dim entTime As Object '保存输入时间 
    Dim xianzaiTime As Object '保存实时时间 
    Dim startTime As Object '保存开始定时时间 
    Dim TimeAdd As Object '时间差
    Private WithEvents mytimer As New DispatcherTimer()
    Private WithEvents mytimers As New DispatcherTimer()

    Public Sub Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles mytimer.Tick '定时关机
        'code here   
        Dim ExitWindows As New ExitWindows
        Select Case TimeMode.SelectedIndex
            Case 0 : ExitWindows.ShutDown()
            Case 1 : ExitWindows.Reboot()
            Case 2 : ExitWindows.LogOff()
        End Select
    End Sub

    Public Sub Ticks(ByVal sender As Object, ByVal e As EventArgs) Handles mytimers.Tick '时间记录器 
        TimeAdds.Text = TimeStri(DateDiff(DateInterval.Second, Now, entTime))
    End Sub

    Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
        If EndTimes.Text <> "" Then
            startTime = Now
            entTime = EndTimes.Text
            TimeAdd = DateDiff(DateInterval.Second, startTime, entTime)
            mytimer.IsEnabled = False
            mytimer.Interval = New TimeSpan(0, 0, 0, 0, TimeAdd * 1000)
            mytimer.IsEnabled = True '启动定时关机
            mytimers.IsEnabled = False
            mytimers.Interval = New TimeSpan(0, 0, 0, 0, 1000)
            mytimers.IsEnabled = True '启动剩余时间记录
        End If
    End Sub

    Public Function TimeStri(Second As Integer) '时间转换(秒→X天 XX:XX:XX)
        Dim s, m, h, d
        s = Second Mod 60
        m = ((Second - s) Mod 60 * 60) / 60
        h = ((Second - s - m * 60) Mod 60 * 60 * 24) / 60 / 60
        d = (Second - s - m * 60 - h * 60 * 60) / (60 * 60 * 24)
        Dim Result As String
        Result = d & "天 " & h & ":" & m & ":" & s
        Return Result
    End Function

    Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
        EndTimes.Text = Now
    End Sub

End Class

Public Class ExitWindows '关机等命令的处理模块
    Public Enum RestartOptions
        LogOff = 0
        PowerOff = 8
        Reboot = 2
        ShutDown = 1
        Suspend = -1
        Hibernate = -2
        'EWX_FORCE = 4
    End Enum

    Public Structure LUID
        Dim LowPart As Integer
        Dim HighPart As Integer
    End Structure

    Public Structure LUID_AND_ATTRIBUTES
        Dim pLuid As LUID
        Dim Attributes As Integer
    End Structure

    Public Structure TOKEN_PRIVILEGES
        Dim PrivilegeCount As Integer
        Dim Privileges As LUID_AND_ATTRIBUTES
    End Structure

    Private Const TOKEN_ADJUST_PRIVILEGES = &H20
    Private Const TOKEN_QUERY = &H8
    Private Const SE_PRIVILEGE_ENABLED = &H2
    Private Const FORMAT_MESSAGE_FROM_SYSTEM = &H1000
    Private Const EWX_FORCE = 4

    'API
    Private Declare Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" (ByVal lpLibFileName As String) As IntPtr
    Private Declare Function FreeLibrary Lib "kernel32" (ByVal hLibModule As IntPtr) As Integer
    Private Declare Function GetProcAddress Lib "kernel32" (ByVal hModule As IntPtr, ByVal lpProcName As String) As IntPtr
    Private Declare Function SetSuspendState Lib "Powrprof" (ByVal Hibernate As Integer, ByVal ForceCritical As Integer, ByVal DisableWakeEvent As Integer) As Integer
    Private Declare Function OpenProcessToken Lib "advapi32.dll" (ByVal ProcessHandle As IntPtr, ByVal DesiredAccess As Integer, ByRef TokenHandle As IntPtr) As Integer
    Private Declare Function LookupPrivilegeValue Lib "advapi32.dll" Alias "LookupPrivilegeValueA" (ByVal lpSystemName As String, ByVal lpName As String, ByRef lpLuid As LUID) As Integer
    Private Declare Function AdjustTokenPrivileges Lib "advapi32.dll" (ByVal TokenHandle As IntPtr, ByVal DisableAllPrivileges As Integer, ByRef NewState As TOKEN_PRIVILEGES, ByVal BufferLength As Integer, ByRef PreviousState As TOKEN_PRIVILEGES, ByRef ReturnLength As Integer) As Integer
    Private Declare Function ExitWindowsEx Lib "user32" (ByVal uFlags As Integer, ByVal dwReserved As Integer) As Integer
    Private Declare Function FormatMessage Lib "kernel32" Alias "FormatMessageA" (ByVal dwFlags As Integer, ByVal lpSource As IntPtr, ByVal dwMessageId As Integer, ByVal dwLanguageId As Integer, ByVal lpBuffer As StringBuilder, ByVal nSize As Integer, ByVal Arguments As Integer) As Integer

    Private Sub ExitWindows(ByVal how As RestartOptions, ByVal force As Boolean)
        Select Case how
            Case RestartOptions.Suspend
                SuspendSystem(False, force)
            Case RestartOptions.Hibernate
                SuspendSystem(True, force)
            Case RestartOptions.ShutDown
                how += RestartOptions.PowerOff
                ExitWindows(Convert.ToInt32(how), force)
            Case Else
                ExitWindows(Convert.ToInt32(how), force)
        End Select
    End Sub

    Private Sub ExitWindows(ByVal how As Integer, ByVal force As Boolean)
        EnableToken("SeShutdownPrivilege")
        If force Then how = how Or EWX_FORCE
        If (ExitWindowsEx(how, 0) = 0) Then Throw New PrivilegeException(FormatError(Marshal.GetLastWin32Error()))
    End Sub

    Private Sub EnableToken(ByVal privilege As String)
        If Not CheckEntryPoint("advapi32.dll", "AdjustTokenPrivileges") Then Return
        Dim tokenHandle As IntPtr = IntPtr.Zero
        Dim privilegeLUID = New LUID
        Dim newPrivileges = New TOKEN_PRIVILEGES
        Dim tokenPrivileges As TOKEN_PRIVILEGES
        If (OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY, tokenHandle)) = 0 Then Throw New PrivilegeException(FormatError(Marshal.GetLastWin32Error()))
        If (LookupPrivilegeValue("", privilege, privilegeLUID)) = 0 Then Throw New PrivilegeException(FormatError(Marshal.GetLastWin32Error()))
        tokenPrivileges.PrivilegeCount = 1
        tokenPrivileges.Privileges.Attributes = SE_PRIVILEGE_ENABLED
        tokenPrivileges.Privileges.pLuid = privilegeLUID
        Dim Size As Integer = 4
        If (AdjustTokenPrivileges(tokenHandle, 0, tokenPrivileges, 4 + (12 * tokenPrivileges.PrivilegeCount), newPrivileges, Size)) = 0 Then Throw New PrivilegeException(FormatError(Marshal.GetLastWin32Error()))
    End Sub

    Private Sub SuspendSystem(ByVal hibernate As Boolean, ByVal force As Boolean)
        If Not CheckEntryPoint("powrprof.dll", "SetSuspendState") Then Throw New PlatformNotSupportedException("The SetSuspendState method is not supported on this system!")
        SetSuspendState(Convert.ToInt32(IIf(hibernate, 1, 0)), Convert.ToInt32(IIf(force, 1, 0)), 0)
    End Sub

    Private Function CheckEntryPoint(ByVal library As String, ByVal method As String) As Boolean
        Dim libPtr As IntPtr = LoadLibrary(library)
        If Not libPtr.Equals(IntPtr.Zero) Then
            If Not GetProcAddress(libPtr, method).Equals(IntPtr.Zero) Then
                FreeLibrary(libPtr)
                Return True
            End If
            FreeLibrary(libPtr)
        End If
        Return False
    End Function

    Private Function FormatError(ByVal number As Integer) As String
        Dim Buffer = New StringBuilder(255)
        FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, IntPtr.Zero, number, 0, Buffer, Buffer.Capacity, 0)
        Return Buffer.ToString()
    End Function

    Public Sub LogOff() '注销
        ExitWindows(RestartOptions.LogOff, False)
    End Sub

    Public Sub Reboot() '重启计算机
        ExitWindows(RestartOptions.Reboot, False)
    End Sub

    Public Sub ShutDown() '关闭系统
        ExitWindows(RestartOptions.ShutDown, False)
    End Sub

    Public Sub ShutDownForce() '强制关闭系统
        ExitWindows(RestartOptions.ShutDown, True)
    End Sub

    Public Sub Suspend() '待机
        ExitWindows(RestartOptions.Suspend, False)
    End Sub

    Public Sub Hibernate() '休眠
        ExitWindows(RestartOptions.Hibernate, False)
    End Sub

End Class

Public Class PrivilegeException

    Inherits Exception

    Public Sub New()
        MyBase.New()
    End Sub

    Public Sub New(ByVal message As String)
        MyBase.New(message)
    End Sub
End Class



 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值