You are on page 1of 58

Editor de Imagens

Height (A) -> textbox1; text=0 Height(C) -> textbox3; text=0 Size (%) -> textbox5; text=100 Maximum=360 DPI(x) -> textbox6; text=0

Width (A) -> textbox2; text=0 Width(C) -> textbox4; text=0 Angle (Degree) -> Nome=angle; Increment=1;

DPI(y) -> textbox7; text=0

Remove Button-> Name=pCls; text=Remove 2XZoom Button-> Name=Button7; text=2X Z00M Progress bar-> Name=PG; Step=1; Visible=false Picturebox1-> Name=picSource; Size Mode=StretchImage Picturebox2-> Name=picDest; Size Mode=StretchImage

Save Dialog-> Name=save; Filter=BMP|*.bmp|EMF|*.emf|EXIF|*.exif|GIF|*.gif|ICO|*.ico|JPEG|*.jpeg|JPG|*.jpg|PNG| *.png|TIFF|*.tiff|WMF|*.wmf OpenfileDialog-> Name=open; filter=Image Files|*.bmp;*.emf;*.exif;*.gif;*.jpeg;*.jpg;*.png;*.tif;*.tiff;*.wmf|All Files|*.*
Imports System.Math Imports System.Drawing Imports System.Drawing.Imaging Imports System.IO Public Class Form1 Dim rathw, ratwh As Double Dim erra As Integer = 0 Dim errb As Integer = 0 Dim path As String Dim col As Color Private Sub btnRotate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRotate.Click Try Dim bm_in As New Bitmap(picSource.Image) Dim wid As Single = bm_in.Width Dim hgt As Single = bm_in.Height Dim corners As Point() = {New Point(0, 0), New Point(wid, 0), New Point(0, hgt), New Point(wid, hgt)} Dim cx As Single = wid / 2 Dim cy As Single = hgt / 2 Dim i As Long For i = 0 To 3 corners(i).X -= cx corners(i).Y -= cy Next i Dim theta As Single = Single.Parse(360 - Angle.Value) * PI / 180.0 Dim sin_theta As Single = Sin(theta) Dim cos_theta As Single = Cos(theta) Dim X As Single Dim Y As Single For i = 0 To 3 X = corners(i).X Y = corners(i).Y corners(i).X = X * cos_theta + Y * sin_theta corners(i).Y = -X * sin_theta + Y * cos_theta Next i Dim xmin As Single = corners(0).X Dim ymin As Single = corners(0).Y For i = 1 To 3 If xmin > corners(i).X Then xmin = corners(i).X If ymin > corners(i).Y Then ymin = corners(i).Y Next i For i = 0 To 3 corners(i).X -= xmin corners(i).Y -= ymin Next i Dim bm_out As New Bitmap(CInt(-2 * xmin), CInt(-2 * ymin)) Dim gr_out As Graphics = Graphics.FromImage(bm_out) ReDim Preserve corners(2) gr_out.DrawImage(bm_in, corners) picDest.Image = bm_out picDest.Show() Button3.Enabled = True

Label2.Text = "Source (*)" Catch MsgBox("Can not rotate the image.", MsgBoxStyle.Exclamation, "Rotate") End Try End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Try Dim m_bitmap As Bitmap = New Bitmap(picSource.Image) m_bitmap.SetResolution(Truncate(CInt(TextBox6.Text)), Truncate(CInt(TextBox7.Text))) picDest.Image = m_bitmap picDest.Show() Button3.Enabled = True Label2.Text = "Source (*)" Catch MsgBox("Can not change the resolution of the picture.", MsgBoxStyle.Exclamation, "DPI Set") End Try End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Try If RadioButton1.Checked = True Then Dim ze As Bitmap = New Bitmap(picSource.Image, Truncate(CInt(TextBox2.Text)), Truncate(CInt(TextBox1.Text))) picDest.Image = ze End If If RadioButton2.Checked = True Then Dim ze As Bitmap = New Bitmap(picSource.Image, Truncate(CInt(TextBox4.Text)), Truncate(CInt(TextBox3.Text))) picDest.Image = ze End If picDest.Show() Button3.Enabled = True Label2.Text = "Source (*)" Catch MsgBox("Can not resize the picture.", MsgBoxStyle.Exclamation, "Resize") End Try End Sub Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click If Open.ShowDialog = Windows.Forms.DialogResult.OK Then Try picSource.Image = Image.FromFile(Open.FileName) inf.Text = "File Size: " + My.Computer.FileSystem.GetFileInfo(Open.FileName).Length.ToString + " bit" + ControlChars.NewLine + "Image Format: " + My.Computer.FileSystem.GetFileInfo(Open.FileName).Extension + ControlChars.NewLine + "Height: " + CStr(picSource.Image.Height) + ControlChars.NewLine + "Width: " + CStr(picSource.Image.Width) + ControlChars.NewLine + "DPIx: " + CStr(picSource.Image.VerticalResolution) + ControlChars.NewLine + "DPIy: " + CStr(picSource.Image.HorizontalResolution) rathw = picSource.Image.Height / picSource.Image.Width ratwh = picSource.Image.Width / picSource.Image.Height TextBox1.Text = picSource.Image.Height TextBox2.Text = picSource.Image.Width

TextBox3.Text = picSource.Image.Height TextBox4.Text = picSource.Image.Width TextBox6.Text = picSource.Image.VerticalResolution TextBox7.Text = picSource.Image.HorizontalResolution TextBox5.Text = "100" TextBox8.Text = "100" Angle.Value = 0 path = Open.FileName picDest.Hide() Tools.Enabled = True Label2.Text = "Source" Catch Open.FileName = path MsgBox("Can not load the image.", MsgBoxStyle.Exclamation, "Image Loading") End Try End If End Sub Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click MsgBox("TImageTools 1.1.0.0" + Chr(13) + "By Mohandes Zalatan" + Chr(13) + "TomyadSoft" + Chr(13) + "IRAN 2008 OpenSource" + Chr(13) + "Blog: tomyad.blogspot.com" + Chr(13) + "E-Mail: mohandes.zalatan@gmail.com", MsgBoxStyle.Information, "About...") End Sub Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged If TextBox1.Focused = False Then Exit Sub Try TextBox2.Text = CInt(TextBox1.Text) * ratwh Catch MsgBox("The value is wrong.", MsgBoxStyle.Exclamation, "Size") End Try End Sub Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged If TextBox2.Focused = False Then Exit Sub Try TextBox1.Text = CInt(TextBox2.Text) * rathw Catch MsgBox("The value is wrong.", MsgBoxStyle.Exclamation, "Size") End Try End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load If WindowState = FormWindowState.Maximized Then WindowState = FormWindowState.Normal End Sub Private Sub TextBox5_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox5.TextChanged Try erra += 1 TextBox1.Text = (CInt(TextBox5.Text) / 100) * CInt(picSource.Image.Height) TextBox2.Text = (CInt(TextBox5.Text) / 100) * CInt(picSource.Image.Width) Catch ex As Exception

If erra > 1 Then MsgBox("The value is wrong.", MsgBoxStyle.Exclamation, "Size") End Try End Sub Private Sub TextBox8_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox8.TextChanged Try errb += 1 TextBox6.Text = (CInt(TextBox8.Text) / 100) * CInt(picSource.Image.VerticalResolution) TextBox7.Text = (CInt(TextBox8.Text) / 100) * CInt(picSource.Image.HorizontalResolution) Catch ex As Exception If errb > 1 Then MsgBox("The value is wrong.", MsgBoxStyle.Exclamation, "DPI") End Try End Sub Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click Save.FileName = "" If Save.ShowDialog <> Windows.Forms.DialogResult.OK Then Exit Sub Try Select Case Save.FilterIndex Case 1 picDest.Image.Save(Save.FileName, ImageFormat.Bmp) Case 2 picDest.Image.Save(Save.FileName, ImageFormat.Emf) Case 3 picDest.Image.Save(Save.FileName, ImageFormat.Exif) Case 4 picDest.Image.Save(Save.FileName, ImageFormat.Gif) Case 5 picDest.Image.Save(Save.FileName, ImageFormat.Icon) Case 6 picDest.Image.Save(Save.FileName, ImageFormat.Jpeg) Case 7 picDest.Image.Save(Save.FileName, ImageFormat.Jpeg) Case 8 picDest.Image.Save(Save.FileName, ImageFormat.Png) Case 9 picDest.Image.Save(Save.FileName, ImageFormat.Tiff) Case 10 picDest.Image.Save(Save.FileName, ImageFormat.Wmf) End Select Catch MsgBox("Can not save the image!", MsgBoxStyle.Exclamation, "Image Saving") End Try End Sub Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click Try picSource.Image.Dispose() picDest.Image.Save(Open.FileName) picSource.Image = Image.FromFile(Open.FileName) inf.Text = "File Size: " + My.Computer.FileSystem.GetFileInfo(Open.FileName).Length.ToString + " bit" + ControlChars.NewLine + "Image Format: " + My.Computer.FileSystem.GetFileInfo(Open.FileName).Extension +

ControlChars.NewLine + "Height: " + CStr(picSource.Image.Height) + ControlChars.NewLine + "Width: " + CStr(picSource.Image.Width) + ControlChars.NewLine + "DPIx: " + CStr(picSource.Image.VerticalResolution) + ControlChars.NewLine + "DPIy: " + CStr(picSource.Image.HorizontalResolution) rathw = picSource.Image.Height / picSource.Image.Width ratwh = picSource.Image.Width / picSource.Image.Height TextBox1.Text = picSource.Image.Height TextBox2.Text = picSource.Image.Width TextBox3.Text = picSource.Image.Height TextBox4.Text = picSource.Image.Width TextBox6.Text = picSource.Image.VerticalResolution TextBox7.Text = picSource.Image.HorizontalResolution TextBox5.Text = 100 TextBox8.Text = 100 Button3.Enabled = False Label2.Text = "Source" Catch ex As Exception MsgBox("Can not save the image! Maybe the image is Read-Only or using by another process.", MsgBoxStyle.Exclamation, "Image Saving") End Try End Sub Private Sub Button7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles pCls.Click Try picDest.Image = picSource.Image For lol As Integer = 0 To picDest.Image.PropertyIdList.Length Try picDest.Image.RemovePropertyItem(picDest.Image.PropertyIdList(lol)) Catch ex As Exception End Try Next picDest.Show() Catch MsgBox("Can not remove the property item of the picture.", MsgBoxStyle.Exclamation, "Property Item") End Try End Sub Private Sub Button7_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button7.Click Try Dim so As New Bitmap(picSource.Image) Dim dt As New Bitmap(so.Width * 2, so.Height * 2) PG.Maximum = so.Width * so.Height PG.Value = 0 PG.Show() For ya As Integer = 0 To so.Height - 1 For xa As Integer = 0 To so.Width - 1 col = so.GetPixel(xa, ya) dt.SetPixel(xa * 2, ya * 2, col) dt.SetPixel(xa * 2 + 1, ya * 2, col) dt.SetPixel(xa * 2, ya * 2 + 1, col) dt.SetPixel(xa * 2 + 1, ya * 2 + 1, col) PG.Value += 1 Next Next picDest.Image = dt Button3.Enabled = True Label2.Text = "Source (*)" picDest.Show()

PG.Hide() Catch MsgBox("Can not Z00M ( 2.X ) the image.", MsgBoxStyle.Exclamation, "2X ZoOm ErOr") End Try End Sub End Class

Informaes do Sistema
Resumo do Sistema

Componentes-> Seleccione uma subcategoria Multimdia->Codecs de udio

Codecs de Video

CDROM

Dispositivo de Som

Visualizao

Infravermelhos Entrada-> Teclado

Dispositivo Apontador

Armazenamento->Unidades

Discos

System Information v2

Public Class System_Information_All_List #Region "Variables" Dim SearchKey As String #End Region #Region "Forms Control" Private Sub System_Information_All_List_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load Me.LabelProductName.Text += My.Application.Info.ProductName.ToString Me.LabelVersion.Text += My.Application.Info.Version.ToString Me.LabelCopyright.Text += My.Application.Info.Copyright.ToString Me.LabelDevelopedBy.Text += My.Application.Info.Trademark.ToString Me.TextBoxDescription.Text = "Description : " & vbCrLf & vbCrLf & My.Application.Info.Description.ToString End Sub #End Region #Region "Computer System Hardware" Private Sub TreeViewComputerSystemHardware_AfterSelect(sender As System.Object, e As System.Windows.Forms.TreeViewEventArgs) Handles TreeViewComputerSystemHardware.AfterSelect Me.Cursor = Cursors.WaitCursor With Me.TreeViewComputerSystemHardware If Not (e.Node.Parent Is Nothing) Then 'Child Node SearchKey = "Win32_" & .SelectedNode.Text.Replace(" ", "") getSystemInfo.Main(Me.SearchKey, Me.lstViewComputerSystemHardware, Me.chkShowNullComputerSystemHardware.Checked) Else 'First Child Node of Parent SearchKey = "Win32_" & .SelectedNode.Nodes.Item(0).Text.Replace(" ", "") getSystemInfo.Main(Me.SearchKey, Me.lstViewComputerSystemHardware, Me.chkShowNullComputerSystemHardware.Checked)

End If End With Me.Cursor = Cursors.Default End Sub Private Sub chkShowNullComputerSystemHardware_Click(sender As System.Object, e As System.EventArgs) Handles chkShowNullComputerSystemHardware.Click Me.Cursor = Cursors.WaitCursor If Me.lstViewComputerSystemHardware.Items.Count > 1 Then If Me.chkShowNullComputerSystemHardware.Checked = False Then getSystemInfo.RemoveNullValueListView(Me.lstViewComputerSystemHardware) Else getSystemInfo.Main(Me.SearchKey, Me.lstViewComputerSystemHardware, Me.chkShowNullComputerSystemHardware.Checked) End If End If Me.Cursor = Cursors.Default End Sub Private Sub bttnSavetoTxtComputerSystemHardware_Click(sender As System.Object, e As System.EventArgs) Handles bttnSavetoTxtComputerSystemHardware.Click If Me.lstViewComputerSystemHardware.Items.Count > 1 Then Me.SaveFileDialog.FileName = SearchKey Me.SaveFileDialog.Filter = "Text File|*.txt" If Me.SaveFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then If Not Me.SaveFileDialog.FileName = Nothing Then Dim myWriter As New IO.StreamWriter(Me.SaveFileDialog.FileName) For Each myItem As ListViewItem In Me.lstViewComputerSystemHardware.Items myWriter.WriteLine(myItem.Text & " : " & myItem.SubItems(1).Text) Next myWriter.Close() MsgBox("Save Data to " & Me.SaveFileDialog.FileName, MsgBoxStyle.Information, "Saved Successfully") End If End If End If End Sub #End Region #Region "Installed Applications" Private Sub tvInstalledApplication_AfterSelect(sender As System.Object, e As System.Windows.Forms.TreeViewEventArgs) Handles tvInstalledApplication.AfterSelect Me.Cursor = Cursors.WaitCursor With Me.tvInstalledApplication 'If No Child Node then Return Selected Node SearchKey = "Win32_" & .SelectedNode.Text.Replace(" ", "") getSystemInfo.Main(Me.SearchKey, Me.lstViewInstalledApplication, Me.chkShowNullValuesInstalledApplication.Checked) End With Me.Cursor = Cursors.Default End Sub Private Sub chkShowNullValuesInstalledApplication_Click(sender As System.Object, e As System.EventArgs) Handles chkShowNullValuesInstalledApplication.Click

Me.Cursor = Cursors.WaitCursor If Me.lstViewInstalledApplication.Items.Count > 1 Then If Me.chkShowNullValuesInstalledApplication.Checked = False Then getSystemInfo.RemoveNullValueListView(Me.lstViewInstalledApplication) Else getSystemInfo.Main(Me.SearchKey, Me.lstViewInstalledApplication, Me.chkShowNullValuesInstalledApplication.Checked) End If End If Me.Cursor = Cursors.Default End Sub Private Sub bttnSaveToTextInstalledApplication_Click(sender As System.Object, e As System.EventArgs) Handles bttnSaveToTextInstalledApplication.Click If Me.lstViewInstalledApplication.Items.Count > 1 Then Me.SaveFileDialog.FileName = SearchKey Me.SaveFileDialog.Filter = "Text File|*.txt" If Me.SaveFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then If Not Me.SaveFileDialog.FileName = Nothing Then Dim myWriter As New IO.StreamWriter(Me.SaveFileDialog.FileName) For Each myItem As ListViewItem In Me.lstViewInstalledApplication.Items myWriter.WriteLine(myItem.Text & " : " & myItem.SubItems(1).Text) Next myWriter.Close() MsgBox("Save Data to " & Me.SaveFileDialog.FileName, MsgBoxStyle.Information, "Saved Successfully") End If End If End If End Sub #End Region #Region "Operating System" Private Sub tvOperatingSystem_AfterSelect(sender As System.Object, e As System.Windows.Forms.TreeViewEventArgs) Handles tvOperatingSystem.AfterSelect Me.Cursor = Cursors.WaitCursor With Me.tvOperatingSystem If Not (e.Node.Parent Is Nothing) Then 'Child Node SearchKey = "Win32_" & .SelectedNode.Text.Replace(" ", "") getSystemInfo.Main(Me.SearchKey, Me.lstViewOperatingSystem, Me.chkShowNullValueOperatingSystem.Checked) Else 'First Child Node of Parent SearchKey = "Win32_" & .SelectedNode.Nodes.Item(0).Text.Replace(" ", "") getSystemInfo.Main(Me.SearchKey, Me.lstViewOperatingSystem, Me.chkShowNullValueOperatingSystem.Checked) End If End With Me.Cursor = Cursors.Default End Sub Private Sub chkShowNullValueOperatingSystem_Click(sender As System.Object, e As System.EventArgs) Handles chkShowNullValueOperatingSystem.Click Me.Cursor = Cursors.WaitCursor If Me.lstViewOperatingSystem.Items.Count > 1 Then If Me.chkShowNullValueOperatingSystem.Checked = False Then

getSystemInfo.RemoveNullValueListView(Me.lstViewOperatingSystem) Else getSystemInfo.Main(Me.SearchKey, Me.lstViewOperatingSystem, Me.chkShowNullValueOperatingSystem.Checked) End If End If Me.Cursor = Cursors.Default End Sub Private Sub bttnSaveTextOperatingSystem_Click(sender As System.Object, e As System.EventArgs) Handles bttnSaveTextOperatingSystem.Click If Me.lstViewOperatingSystem.Items.Count > 1 Then Me.SaveFileDialog.FileName = SearchKey Me.SaveFileDialog.Filter = "Text File|*.txt" If Me.SaveFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then If Not Me.SaveFileDialog.FileName = Nothing Then Dim myWriter As New IO.StreamWriter(Me.SaveFileDialog.FileName) For Each myItem As ListViewItem In Me.lstViewOperatingSystem.Items myWriter.WriteLine(myItem.Text & " : " & myItem.SubItems(1).Text) Next myWriter.Close() MsgBox("Save Data to " & Me.SaveFileDialog.FileName, MsgBoxStyle.Information, "Saved Successfully") End If End If End If End Sub #End Region #Region "Performance Counter" Private Sub tvPerformanceCounter_AfterSelect(sender As System.Object, e As System.Windows.Forms.TreeViewEventArgs) Handles tvPerformanceCounter.AfterSelect Me.Cursor = Cursors.WaitCursor With Me.tvPerformanceCounter If Not (e.Node.Parent Is Nothing) Then 'Child Node If e.Node.Parent.Text = "Formatted Performance Counter" Then SearchKey = "Win32_PerfFormatted" & .SelectedNode.Text.Replace(" ", "") ElseIf e.Node.Parent.Text = "Raw Performance Counter" Then SearchKey = "Win32_PerfRaw" & .SelectedNode.Text.Replace(" ", "") End If getSystemInfo.Main(Me.SearchKey, Me.lstViewPerformanceCounter, Me.chkShowNullValuesPerformanceCounter.Checked) Else 'First Child Node of Parent If e.Node.Text = "Formatted Performance Counter" Then SearchKey = "Win32_PerfFormatted" & .SelectedNode.Nodes.Item(0).Text.Replace(" ", "") ElseIf e.Node.Text = "Raw Performance Counter" Then SearchKey = "Win32_PerfRaw" & .SelectedNode.Nodes.Item(0).Text.Replace(" ", "") End If getSystemInfo.Main(Me.SearchKey, Me.lstViewPerformanceCounter, Me.chkShowNullValuesPerformanceCounter.Checked) End If End With Me.Cursor = Cursors.Default

End Sub Private Sub chkShowNullValuesPerformanceCounter_Click(sender As System.Object, e As System.EventArgs) Handles chkShowNullValuesPerformanceCounter.Click Me.Cursor = Cursors.WaitCursor If Me.lstViewPerformanceCounter.Items.Count > 1 Then If Me.chkShowNullValuesPerformanceCounter.Checked = False Then getSystemInfo.RemoveNullValueListView(Me.lstViewPerformanceCounter) Else getSystemInfo.Main(Me.SearchKey, Me.lstViewPerformanceCounter, Me.chkShowNullValuesPerformanceCounter.Checked) End If End If Me.Cursor = Cursors.Default End Sub Private Sub bttnSaveTextPerformanceCounter_Click(sender As System.Object, e As System.EventArgs) Handles bttnSaveTextPerformanceCounter.Click If Me.lstViewPerformanceCounter.Items.Count > 1 Then Me.SaveFileDialog.FileName = SearchKey Me.SaveFileDialog.Filter = "Text File|*.txt" If Me.SaveFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then If Not Me.SaveFileDialog.FileName = Nothing Then Dim myWriter As New IO.StreamWriter(Me.SaveFileDialog.FileName) For Each myItem As ListViewItem In Me.lstViewPerformanceCounter.Items myWriter.WriteLine(myItem.Text & " : " & myItem.SubItems(1).Text) Next myWriter.Close() MsgBox("Save Data to " & Me.SaveFileDialog.FileName, MsgBoxStyle.Information, "Saved Successfully") End If End If End If End Sub #End Region #Region "Security Descriptor Helper" Private Sub tvSecurityDescriptorHelper_AfterSelect(sender As System.Object, e As System.Windows.Forms.TreeViewEventArgs) Handles tvSecurityDescriptorHelper.AfterSelect Me.Cursor = Cursors.WaitCursor With Me.tvSecurityDescriptorHelper 'If No Child Node then Return Selected Node SearchKey = "Win32_" & .SelectedNode.Text.Replace(" ", "") getSystemInfo.Main(Me.SearchKey, Me.lstViewSecurityDescriptorHelper, Me.chkShowNullValuesSecurityDescriptorHelper.Checked) End With Me.Cursor = Cursors.Default End Sub Private Sub chkShowNullValuesSecurityDescriptorHelper_Click(sender As System.Object, e As System.EventArgs) Handles chkShowNullValuesSecurityDescriptorHelper.Click Me.Cursor = Cursors.WaitCursor If Me.lstViewSecurityDescriptorHelper.Items.Count > 1 Then If Me.chkShowNullValuesSecurityDescriptorHelper.Checked = False Then getSystemInfo.RemoveNullValueListView(Me.lstViewSecurityDescriptorHelper) Else

getSystemInfo.Main(Me.SearchKey, Me.lstViewSecurityDescriptorHelper, Me.chkShowNullValuesSecurityDescriptorHelper.Checked) End If End If Me.Cursor = Cursors.Default End Sub Private Sub bttnSaveTextSecurityDescriptorHelper_Click(sender As System.Object, e As System.EventArgs) Handles bttnSaveTextSecurityDescriptorHelper.Click If Me.lstViewSecurityDescriptorHelper.Items.Count > 1 Then Me.SaveFileDialog.FileName = SearchKey Me.SaveFileDialog.Filter = "Text File|*.txt" If Me.SaveFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then If Not Me.SaveFileDialog.FileName = Nothing Then Dim myWriter As New IO.StreamWriter(Me.SaveFileDialog.FileName) For Each myItem As ListViewItem In Me.lstViewSecurityDescriptorHelper.Items myWriter.WriteLine(myItem.Text & " : " & myItem.SubItems(1).Text) Next myWriter.Close() MsgBox("Save Data to " & Me.SaveFileDialog.FileName, MsgBoxStyle.Information, "Saved Successfully") End If End If End If End Sub #End Region #Region "WMI Service Management" Private Sub tvWMIServiceManagement_AfterSelect(sender As System.Object, e As System.Windows.Forms.TreeViewEventArgs) Handles tvWMIServiceManagement.AfterSelect Me.Cursor = Cursors.WaitCursor With Me.tvWMIServiceManagement If Not (e.Node.Parent Is Nothing) Then 'Child Node SearchKey = "Win32_" & .SelectedNode.Text.Replace(" ", "") getSystemInfo.Main(Me.SearchKey, Me.lstViewWMIServiceManagement, Me.chkShowNullValuesWMIServiceManagement.Checked) Else 'First Child Node of Parent SearchKey = "Win32_" & .SelectedNode.Nodes.Item(0).Text.Replace(" ", "") getSystemInfo.Main(Me.SearchKey, Me.lstViewWMIServiceManagement, Me.chkShowNullValuesWMIServiceManagement.Checked) End If End With Me.Cursor = Cursors.Default End Sub Private Sub chkShowNullValuesWMIServiceManagement_Click(sender As System.Object, e As System.EventArgs) Handles chkShowNullValuesWMIServiceManagement.Click Me.Cursor = Cursors.WaitCursor If Me.lstViewWMIServiceManagement.Items.Count > 1 Then If Me.chkShowNullValuesWMIServiceManagement.Checked = False Then getSystemInfo.RemoveNullValueListView(Me.lstViewWMIServiceManagement)

Else getSystemInfo.Main(Me.SearchKey, Me.lstViewWMIServiceManagement, Me.chkShowNullValuesWMIServiceManagement.Checked) End If End If Me.Cursor = Cursors.Default End Sub Private Sub bttnSaveTextWMIServiceManagement_Click(sender As System.Object, e As System.EventArgs) Handles bttnSaveTextWMIServiceManagement.Click If Me.lstViewWMIServiceManagement.Items.Count > 1 Then Me.SaveFileDialog.FileName = SearchKey Me.SaveFileDialog.Filter = "Text File|*.txt" If Me.SaveFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then If Not Me.SaveFileDialog.FileName = Nothing Then Dim myWriter As New IO.StreamWriter(Me.SaveFileDialog.FileName) For Each myItem As ListViewItem In Me.lstViewWMIServiceManagement.Items myWriter.WriteLine(myItem.Text & " : " & myItem.SubItems(1).Text) Next myWriter.Close() MsgBox("Save Data to " & Me.SaveFileDialog.FileName, MsgBoxStyle.Information, "Saved Successfully") End If End If End If End Sub #End Region

End Class

getSystemInfo.vb(classe)
Imports System.Management Public Class getSystemInfo Public Overloads Shared Function Main(ByVal SearchKey As String, ByVal lstView As ListView, ByVal AddNullValue As Boolean) As Integer lstView.Items.Clear() Dim pFlgDataExist As Boolean = False Dim ms As New ManagementScope 'Dim Searcher As New ManagementObjectSearcher(ms.Path.ToString, "SELECT * FROM " & SearchKey, New EnumerationOptions(Nothing, System.TimeSpan.Zero, 1, True, False, True, True, False, True, True)) Dim Searcher As New ManagementObjectSearcher("SELECT * FROM " & SearchKey) Try For Each mngObj As ManagementObject In Searcher.Get() pFlgDataExist = True Dim Group As ListViewGroup Try Group = lstView.Groups.Add(mngObj("Name").ToString(), mngObj("Name").ToString()) Catch

Group = lstView.Groups.Add(mngObj.ToString(), mngObj.ToString()) End Try If mngObj.Properties.Count <= 0 Then MsgBox("No Information Currently Available", MsgBoxStyle.Information, "No Info to Display") Exit Function End If For Each PD As PropertyData In mngObj.Properties Dim item As New ListViewItem(Group) If Not lstView.Items.Count Mod 2 = 0 Then item.BackColor = Color.White Else item.BackColor = Color.WhiteSmoke End If item.Text = PD.Name If PD.Value IsNot Nothing AndAlso PD.Value.ToString() <> "" Then Select Case PD.Value.GetType().ToString() Case "System.String[]" Dim StrMain As String() = DirectCast(PD.Value, String()) Dim strDisplay As String = "" For Each st As String In StrMain strDisplay += st & " " Next item.SubItems.Add(strDisplay) Exit Select Case "System.UInt16[]" Dim ShortMain As UShort() = DirectCast(PD.Value, UShort()) Dim strDisplay As String = "" For Each st As UShort In ShortMain strDisplay += st.ToString() & " " Next item.SubItems.Add(strDisplay) Exit Select Case Else item.SubItems.Add(PD.Value.ToString()) Exit Select End Select Else If AddNullValue = True Then item.SubItems.Add("No Information Available to Display") Else Continue For End If End If lstView.Items.Add(item) Next Next

Catch ex As Exception MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Error on Getting Information") End Try If pFlgDataExist = False Then Dim Group As ListViewGroup Group = lstView.Groups.Add("No Information Available to Display", "No Information Available to Display") Dim item As New ListViewItem(Group) lstView.Items.Add(item) End If End Function Public Overloads Shared Sub RemoveNullValueListView(lstView As ListView) For Each item As ListViewItem In lstView.Items If item.SubItems(1).Text = "No Information Available to Display" Then item.Remove() End If Next End Sub 'For Single Item from WMI Win32 Object ' Dim Searcher As New ManagementObjectSearcher("SELECT Model FROM Win32_DiskDrive") ' For Each MO As ManagementObject In Searcher.Get() ' For Each PD As PropertyData In MO.Properties ' Me.TextBox1.Text = "HDD Model : " & PD.Value.ToString ' Next ' Next

End Class

SplashScreen.vb

Public NotInheritable Class SplashScreen

'TODO: This form can easily be set as the splash screen for the application by going to the "Application" tab ' of the Project Designer ("Properties" under the "Project" menu).

Private Sub SplashScreen_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load lblDescription.Text = My.Application.Info.Description Version.Text = Version.Text & System.String.Format("{0}", My.Application.Info.Version.ToString) ' My.Application.Info.Version.Major, My.Application.Info.Version.Minor) 'Copyright info Copyright.Text = My.Application.Info.Copyright End Sub

End Class

Computer System Hardware

Descrio: NeuroSoft Sotfware House & IT Centre" & vbcrlf & "Abbottabad - Pakistan" & vbcrlf & "Contact : +92-333-(200)8387" & vbCrlf & "Email : pkishar

shutdownTimer PC

Timer1-> Interval=1000; Enable=false

Combobox Items-> Log Off(mudar de utilizador); Power Off(terminar sesso); Reboot(reiniciar); Shutdown(encerrar); Suspend(suspender); Hybernate(hibernar) Panel1; Dock=bottom Panel2; dock=right

Imports Imports Imports Imports Imports Imports Imports

System.ServiceProcess System.Threading System System.Drawing System.Collections System.ComponentModel System.Windows.Forms

Public Class Main Inherits System.Windows.Forms.Form

Public Sub New() MyBase.New() 'This call is required by the Windows Form Designer. 'Skybound.VisualStyles.VisualStyleProvider.EnableVisualStyles() InitializeComponent() taskbarNotifier1 = New TaskBarNotifier taskbarNotifier1.SetBackgroundBitmap(New Bitmap(MyClass.GetType(), "popup.bmp"), Color.FromArgb(255, 0, 255)) taskbarNotifier1.SetCloseBitmap(New Bitmap(MyClass.GetType(), "close.bmp"), Color.FromArgb(255, 0, 255), New Point(215, 8)) taskbarNotifier1.TitleRectangle = New Rectangle(60, 20, 180, 25) taskbarNotifier1.TextRectangle = New Rectangle(1, 10, 243, 110) 'Add any initialization after the InitializeComponent() call End Sub 'Form overrides dispose to clean up the component list. Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) If disposing Then If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(disposing) End Sub

Dim PopHide As Boolean = False Dim Notify As Boolean = False Private WithEvents taskbarNotifier1 As TaskBarNotifier Dim hours, mins, seconds As Integer Dim setHours, setMins As Integer Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load End Sub Private Sub btnHide_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHide.Click Me.Hide() End Sub Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick Timer1.Start()

lblTime.Text = Now.Day.ToString + "/" + Now.Month.ToString + "/" + Now.Year.ToString + " " + _ formatTo2Digits(Now.Hour) + ":" + formatTo2Digits(Now.Minute) + ":" + formatTo2Digits(Now.Second) If rbtnAt.Checked = True Then ShutdownAt() ElseIf rbtnIn.Checked = True Then ShutdownIn() End If End Sub Private Declare Auto Function PlaySound Lib "winmm.dll" (ByVal SoundName As String, _ ByVal hModule As Integer, ByVal dwFlags As Integer) As Integer Private Sub PlayNow() Dim fileName As String = String.Concat(Application.StartupPath + "\shutdown.wav") Const SND_FILENAME As Integer = &H20000 PlaySound(fileName, 0, SND_FILENAME) End Sub Private Sub ShutdownIn() If hours > 0 Or mins > 0 Or seconds > 0 Then If mins = 0 AndAlso hours > 0 Then _ mins = 59 : hours = hours - 1 If seconds = 0 AndAlso mins > 0 Then _ seconds = 60 : mins = mins - 1 seconds = seconds - 1 End If lblShutdownType.Text = cbSelect.Text + " in" lblTimeTo.Text = formatTo2Digits(hours) + ":" + formatTo2Digits(mins) + ":" + formatTo2Digits(seconds) If hours = 0 AndAlso mins = 0 AndAlso seconds < 60 Then Dim remain As Integer = seconds If PopHide = False Then showPopup(cbSelect.Text, remain) If Notify = False Then PlayNow() Notify = True End If End If If hours = 0 AndAlso mins = 0 AndAlso seconds = 0 Then Me.Show() Timer1.Stop() Select Case cbSelect.SelectedIndex Case 0 Me.Close() WindowsController.ExitWindows(RestartOptions.LogOff, True) Case 1 Me.Close() WindowsController.ExitWindows(RestartOptions.PowerOff, True) Case 2 Me.Close() WindowsController.ExitWindows(RestartOptions.Reboot, True)

Case 3 Me.Close() WindowsController.ExitWindows(RestartOptions.ShutDown, True) Case 4 Me.Close() WindowsController.ExitWindows(RestartOptions.Suspend, True) Case 5 Me.Close() WindowsController.ExitWindows(RestartOptions.Hibernate, True) End Select End If End Sub Private Function formatTo2Digits(ByVal Val As Integer) As String Dim newVal As String Dim len As Integer = Val.ToString.Length If len = 1 newVal Return Else Return End If End Function Then = "0" + Val.ToString newVal Val.ToString

Private Sub ShutdownAt() lblShutdownType.Text = cbSelect.Text + " at" lblTimeTo.Text = formatTo2Digits(nudHours1.Value) + ":" + formatTo2Digits(nudMin1.Value) + ":" + formatTo2Digits(0) 'special case of set min = 0 and one less is 59 Dim warningTime As Integer If nudMin1.Value = 0 Then warningTime = 59 Else warningTime = nudMin1.Value - 1 End If

If String.Compare(Now.Hour.ToString, nudHours1.Value.ToString) = 0 Then If String.Compare(Now.Minute.ToString, warningTime.ToString) = 0 Then Dim remain As Integer = 60 - Now.Second If PopHide = False Then showPopup(cbSelect.Text, remain) If Notify = False Then PlayNow() Notify = True End If End If End If If String.Compare(Now.Hour.ToString, nudHours1.Value.ToString) = 0 Then If String.Compare(Now.Minute.ToString, nudMin1.Value.ToString) = 0 Then Me.Show() Timer1.Stop() Select Case cbSelect.SelectedIndex Case 0 Me.Close() WindowsController.ExitWindows(RestartOptions.LogOff, True) Case 1 Me.Close()

WindowsController.ExitWindows(RestartOptions.PowerOff, True) Case 2 Me.Close() WindowsController.ExitWindows(RestartOptions.Reboot, True) Case 3 Me.Close() WindowsController.ExitWindows(RestartOptions.ShutDown, True) Case 4 Me.Close() WindowsController.ExitWindows(RestartOptions.Suspend, True) Case 5 Me.Close() WindowsController.ExitWindows(RestartOptions.Hibernate, True) End Select End If End If End Sub Private Sub Notifier_CloseButtonClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles taskbarNotifier1.CloseButtonClick taskbarNotifier1.Hide() PopHide = True End Sub Private Sub Notifier_TitleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles taskbarNotifier1.TitleClick Timer1.Stop() End Sub Private Sub Notifier_TextClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles taskbarNotifier1.TextClick Timer1.Stop() End Sub Private Sub showPopup(ByVal shutDownType As String, ByVal remain As Integer) With taskbarNotifier1 .CloseButtonClickEnabled = True .TitleClickEnabled = False .TextClickEnabled = True .DrawTextFocusRect = False .KeepVisibleOnMouseOver = True .ReShowOnMouseOver = True .Show("Auto Shutdown Notice", "Sistema" + shutDownType + " in " + remain.ToString + " Seconds " & _ "Cliquie na caixa para Paralizar o processo", 500, 3000, 500) End With End Sub Private Sub btnOk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOk.Click Timer1.Enabled = True Timer1.Start() Notify = False lblTime.Visible = True lblTime.Visible = True setHours = nudHours2.Value setMins = nudMin2.Value

hours = setHours mins = setMins If nudHours2.Value = 0 AndAlso nudMin2.Value = 0 Then seconds = 60 Else seconds = 0 End If btnOk.Enabled = False End Sub Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click Timer1.Stop() Application.Exit() End Sub Private Sub cbSelect_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbSelect.SelectedIndexChanged Timer1.Stop() btnOk.Enabled = True End Sub

Private Sub nudHours_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles nudHours1.ValueChanged Timer1.Stop() If nudHours1.Value = nudHours1.Maximum Then nudHours1.UpButton() nudHours1.Value = nudHours1.Minimum + 1 End If If nudHours1.Value = nudHours1.Minimum Then nudHours1.DownButton() nudHours1.Value = nudHours1.Maximum - 1 End If If Not String.Compare(cbSelect.Text, "") = 0 Then btnOk.Enabled = True End If End Sub Private Sub nudMin_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles nudMin1.ValueChanged Timer1.Stop() If nudMin1.Value = nudMin1.Maximum Then nudMin1.UpButton() nudMin1.Value = nudMin1.Minimum + 1 End If If nudMin1.Value = nudMin1.Minimum Then nudMin1.DownButton() nudMin1.Value = nudMin1.Maximum - 1 End If If Not String.Compare(cbSelect.Text, "") = 0 Then btnOk.Enabled = True End If End Sub Private Sub MenuItem3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem3.Click Timer1.Stop()

Application.Exit() End Sub Private Sub MenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem2.Click Me.Show() WindowState = FormWindowState.Normal Timer1.Stop() End Sub Private Sub MenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem1.Click Me.Show() WindowState = FormWindowState.Normal End Sub Private Sub NotifyIcon1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles NotifyIcon1.DoubleClick Me.Show() WindowState = FormWindowState.Normal End Sub

Private Sub nudHours2_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles nudHours2.ValueChanged Timer1.Stop() If nudHours2.Value = nudHours2.Maximum Then nudHours2.UpButton() nudHours2.Value = nudHours2.Minimum + 1 End If If nudHours2.Value = nudHours2.Minimum Then nudHours2.DownButton() nudHours2.Value = nudHours2.Maximum - 1 End If If Not String.Compare(cbSelect.Text, "") = 0 Then btnOk.Enabled = True End If End Sub Private Sub nudMin2_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles nudMin2.ValueChanged Timer1.Stop() If nudMin2.Value = nudMin2.Maximum Then nudMin2.UpButton() nudMin2.Value = nudMin2.Minimum + 1 End If If nudMin2.Value = nudMin2.Minimum Then nudMin2.DownButton() nudMin2.Value = nudMin2.Maximum - 1 End If If Not String.Compare(cbSelect.Text, "") = 0 Then btnOk.Enabled = True End If End Sub Private Sub rbtnAt_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbtnAt.CheckedChanged nudHours1.Enabled = True nudMin1.Enabled = True nudHours2.Enabled = False

nudMin2.Enabled = False Timer1.Stop() If Not String.Compare(cbSelect.Text, "") = 0 Then btnOk.Enabled = True End If End Sub Private Sub rbtnIn_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbtnIn.CheckedChanged nudHours1.Enabled = False nudMin1.Enabled = False nudHours2.Enabled = True nudMin2.Enabled = True Timer1.Stop() If Not String.Compare(cbSelect.Text, "") = 0 Then btnOk.Enabled = True End If End Sub End Class

Imports Imports Imports Imports Imports Imports Imports Imports

System System.ComponentModel System.Drawing System.Drawing.Imaging System.Drawing.Drawing2D System.Windows.Forms System.Reflection System.Runtime.InteropServices

'##SUMMARY Class which allows to display Messenger style or other Skinned instant messaging popups '##REMARKS This code was originally written in C# and ported/modified to VB.NET.<br> '##REMARKS Special Credits to John O'Byrne who write the original TaskBarNotifier Class in C#. '##REMARKS <br> '##REMARKS _<b>Date</b>:06/01/03 &nbsp;&nbsp; <b>Rev</b>: 001<br> '##REMARKS _<i>Initial Version ported from C#.</i><br> '##REMARKS <i>Small modification where applied to the variable names in order to reflect my personal naming standards</i> '##REMARKS <i>Modified the way of event notification to work with Delegates and RaiseEvent.</i>

'##REMARKS <i>Modified the Focus rectangle drawing. It now draws a DarkGrey Solid border instead of the Etched '##REMARKS _style rectangle that was originally used by John O'Byrne</i> '##REMARKS <br> '##REMARKS _<b>Date</b>:10/01/03 &nbsp;&nbsp; <b>Rev</b>: 002<br> '##REMARKS <i>Update: Added KeepVisibleOnMouseOver property. '##REMARKS <i>Whenever the mouse is over the popup window, it will remain visible. '##REMARKS _In the previous version, even if the mouse is over the window, it still was hidden when the '##REMARKS _iVisibleEvents time expired.</i> '##REMARKS <i>Update: Added ReShowOnMouseOver property</i> '##REMARKS <i>If you move the mouse back over the popup while it is disappearing, it will now '##REMARKS _re-appear again. Basically, if the popup is hiding itself, when the mouse moves over it, '##REMARKS _it is re-shown.</i> Public Class TaskBarNotifier Inherits System.Windows.Forms.Form '##SUMMARY Win32 API Call Declaration which will actually show the TaskBarNotifier window. <DllImport("User32")> _ Private Shared Function ShowWindow(ByVal hWnd As IntPtr, ByVal nCmdShow As Int32) As Boolean End Function

'##SUMMARY Delegate which defines the signature of a CloseButtonClick event handler. Public Delegate Sub CloseClickHandler(ByVal sender As Object, ByVal e As EventArgs) '##SUMMARY Delegate which defines the signature of a TitleClick event handler. Public Delegate Sub TitleClickHandler(ByVal sender As Object, ByVal e As EventArgs) '##SUMMARY Delegate which defines the signature of a TextClick event handler. Public Delegate Sub TextClickHandler(ByVal sender As Object, ByVal e As EventArgs) '##SUMMARY Event which is triggered when the CloseButton region of the TaskbarNotifierWindow is clicked. '##REMARKS This event is only triggered if the 'CloseButtonClickEnabled' property is True. Public Event CloseButtonClick As CloseClickHandler '##SUMMARY Event which is triggered when the Title text region of the TaskbarNotifierWindow is clicked. '##REMARKS This event is only triggered if the 'TitleClickEnabled' property is True. Public Event TitleClick As TitleClickHandler '##SUMMARY Event which is triggered when the inner Text region of the TaskbarNotifierWindow is clicked. '##REMARKS This event is only triggered if the 'TextClickEnabled' property is True. Public Event TextClick As TextClickHandler #Region "Protected Members"

Protected _bmpBackground As Bitmap = Nothing Protected _bmpCloseButton As Bitmap = Nothing Protected _ptCloseButtonLocation As Point Protected _sizCloseButtonSize As Size Protected _rectRealTitle As Rectangle Protected _rectRealText As Rectangle Protected _rectWorkArea As Rectangle Protected _tmrAnimation As New Timer Protected _eWindowState As TaskbarStates = TaskbarStates.Hidden Protected _sTitle As String Protected _sText As String Protected _colTitleNormal As Color = Color.Red Protected _colTitleHover As Color = Color.Red Protected _colTextNormal As Color = Color.Black Protected _colTextHover As Color = Color.SlateBlue Protected _fntTitleNormal As Font = New Font("Tahoma", 13, FontStyle.Bold, GraphicsUnit.Pixel) Protected _fntTitleHover As Font = New Font("Tahoma", 13, FontStyle.Regular, GraphicsUnit.Pixel) Protected _fntTextNormal As Font = New Font("Tahoma", 13, FontStyle.Regular, GraphicsUnit.Pixel) Protected _fntTextHover As Font = New Font("Tahoma", 13, FontStyle.Underline, GraphicsUnit.Pixel) Protected _iShowEvents As Integer Protected _iHideEvents As Integer Protected _iVisibleEvents As Integer Protected _iIncrementShow As Integer Protected _iIncrementHide As Integer ' Rev 002: Added Property Members Protected _bKeepVisibleOnMouseOver As Boolean = True Protected _bReShowOnMouseOver As Boolean = False ' Mouse State Indicators Protected _bMouseOverPopup As Boolean = False Protected _bMouseOverClose As Boolean = False Protected _bMouseOverText As Boolean = False Protected _bMouseOverTitle As Boolean = False Protected _bMouseDown As Boolean = False Protected _bCloseButtonClickEnabled As Boolean = True Protected _bTitleClickEnabled As Boolean = False Protected _bTextClickEnabled As Boolean = True Protected Protected Protected Protected Protected #End Region #Region "Enums" '##SUMMARY List of the different popup animation status Public Enum TaskbarStates '##MEMBER Indicates the the TaskbarNotifierWindow is hidden. Hidden = 0 '##MEMBER Indicates the the TaskbarNotifierWindow in proces of being shown (appearing). Appearing = 1 '##MEMBER Indicates the the TaskbarNotifierWindow is visible. _rectTitle As Rectangle _rectText As Rectangle _bDrawFocusRect As Boolean = True _eFocusRectStyle As ButtonBorderStyle = ButtonBorderStyle.Solid _colFocusRect As Color = Color.DarkGray

Visible = 2 '##MEMBER Indicates the the TaskbarNotifierWindow in proces of being hidden (disappearing). Disappearing = 3 End Enum #End Region #Region "Constructor" Public Sub New() ' Window Style FormBorderStyle = FormBorderStyle.None WindowState = FormWindowState.Minimized MyBase.Show() MyBase.Hide() WindowState = FormWindowState.Normal ShowInTaskbar = False TopMost = True MaximizeBox = False MinimizeBox = False ControlBox = False Me.SetStyle(ControlStyles.CacheText, True) _tmrAnimation.Enabled = True AddHandler _tmrAnimation.Tick, AddressOf OnTimer End Sub #End Region #Region "Public Properties" '##SUMMARY Get the current TaskbarState (hidden, showing, visible, hiding) Public ReadOnly Property TaskBarState() As TaskbarStates Get Return Me._eWindowState End Get End Property '##SUMMARY Get/Set the popup Title Text Public Property TitleText() As String Get Return Me._sTitle End Get Set(ByVal Value As String) Me._sTitle = Value Refresh() End Set End Property '##SUMMARY Get/Set the popup Content Text Public Property ContentText() As String Get Return Me._sText End Get Set(ByVal Value As String) Me._sText = Value Refresh() End Set End Property

'##SUMMARY Get/Set the Normal Title Color Public Property NormalTitleColor() As Color Get Return Me._colTitleNormal End Get Set(ByVal Value As Color) Me._colTitleNormal = Value Refresh() End Set End Property '##SUMMARY Get/Set the Hover Title Color Public Property HoverTitleColor() As Color Get Return Me._colTitleHover End Get Set(ByVal Value As Color) Me._colTitleHover = Value Refresh() End Set End Property '##SUMMARY Get/Set the Normal Content Color Public Property NormalContentColor() As Color Get Return Me._colTextNormal End Get Set(ByVal Value As Color) Me._colTextNormal = Value Refresh() End Set End Property '##SUMMARY Get/Set the Hover Content Color Public Property HoverContentColor() As Color Get Return Me._colTextHover End Get Set(ByVal Value As Color) Me._colTextHover = Value Refresh() End Set End Property '##SUMMARY Get/Set the Normal Title Font Public Property NormalTitleFont() As Font Get Return Me._fntTitleNormal End Get Set(ByVal Value As Font) Me._fntTitleNormal = Value Refresh() End Set End Property

'##SUMMARY Get/Set the Hover Title Font Public Property HoverTitleFont() As Font Get Return Me._fntTitleHover End Get

Set(ByVal Value As Font) Me._fntTitleHover = Value Refresh() End Set End Property '##SUMMARY Get/Set the Normal Content Font Public Property NormalContentFont() As Font Get Return Me._fntTextNormal End Get Set(ByVal Value As Font) Me._fntTextNormal = Value Refresh() End Set End Property '##SUMMARY Get/Set the Hover Content Font Public Property HoverContentFont() As Font Get Return Me._fntTextHover End Get Set(ByVal Value As Font) Me._fntTextHover = Value Refresh() End Set End Property '##SUMMARY Activates/Deactivates the CloseButtonClick event raising. < _ DefaultValue(True) _ > _ Public Property CloseButtonClickEnabled() As Boolean Get Return Me._bCloseButtonClickEnabled End Get Set(ByVal Value As Boolean) Me._bCloseButtonClickEnabled = Value End Set End Property '##SUMMARY Activates/Deactivates the TitleClick event raising < _ DefaultValue(False) _ > _ Public Property TitleClickEnabled() As Boolean Get Return Me._bTitleClickEnabled End Get Set(ByVal Value As Boolean) Me._bTitleClickEnabled = Value End Set End Property '##SUMMARY Activates/Deactivates the TextClick event raising < _ DefaultValue(True) _ > _ Public Property TextClickEnabled() As Boolean Get Return Me._bTextClickEnabled End Get

Set(ByVal Value As Boolean) Me._bTextClickEnabled = Value End Set End Property '##SUMMARY Returns or sets the Rectangle reserved for the Title of the window. Public Property TitleRectangle() As Rectangle Get Return Me._rectTitle End Get Set(ByVal Value As Rectangle) Me._rectTitle = Value End Set End Property '##SUMMARY Returns or sets the Rectangle reserved for the Text content of the window. Public Property TextRectangle() As Rectangle Get Return Me._rectText End Get Set(ByVal Value As Rectangle) Me._rectText = Value End Set End Property '##SUMMARY Indicates if the focus rectangle should be draws when the mouse moves over the Title or Text < _ DefaultValue(True) _ > _ Public Property DrawTextFocusRect() As Boolean Get Return Me._bDrawFocusRect End Get Set(ByVal Value As Boolean) Me._bDrawFocusRect = Value End Set End Property '##SUMMARY Returns or sets the Style of the TextFocusRect < _ DefaultValue(System.Windows.Forms.ButtonBorderStyle.Dotted) _ > _ Public Property TextFocusRectStyle() As ButtonBorderStyle Get Return Me._eFocusRectStyle End Get Set(ByVal Value As ButtonBorderStyle) Me._eFocusRectStyle = Value End Set End Property '##SUMMARY Returns or sets the Color of the TextFocusRect Public Property TextFocusRectColor() As Color Get Return Me._colFocusRect End Get Set(ByVal Value As Color) Me._colFocusRect = Value End Set

End Property '##SUMMARY Indicates if the TaskBarNotifier window remains statically '##SUMMARY _visible while the mouse pointer is over it. (Rev 002) < _ DefaultValue(True) _ > _ Public Property KeepVisibleOnMouseOver() As Boolean Get Return Me._bKeepVisibleOnMouseOver End Get Set(ByVal Value As Boolean) Me._bKeepVisibleOnMouseOver = Value End Set End Property '##SUMMARY Indicates that the TaskBarNotifier window should be re-appearing if the mouse pointer '##SUMMARY _moves over it while it is in the proces of hiding itself. (Rev 002) < _ DefaultValue(False) _ > _ Public Property ReShowOnMouseOver() As Boolean Get Return Me._bReShowOnMouseOver End Get Set(ByVal Value As Boolean) Me._bReShowOnMouseOver = Value End Set End Property #End Region #Region "Public Methods" '##SUMMARY Displays the popup for a certain amount of time '##PARAM strTitle The string which will be shown as the title of the popup. '##PARAM strContent The string which will be shown as the content of the popup. '##PARAM nTimeToShow Duration of the showing animation (in milliseconds). '##PARAM nTimeToStay Duration of the visible state before collapsing (in milliseconds). '##PARAM nTimeToHide Duration of the hiding animation (in milliseconds). Public Shadows Sub Show(ByVal strTitle As String, ByVal strContent As String, _ ByVal nTimeToShow As Integer, _ ByVal nTimeToStay As Integer, _ ByVal nTimeToHide As Integer) Me._rectWorkArea = Screen.GetWorkingArea(Me._rectWorkArea) Me._sTitle = strTitle Me._sText = strContent Me._iVisibleEvents = nTimeToStay CalculateMouseRectangles() ' We calculate the pixel increment and the timer value for the showing animation Dim nEvents As Integer If nTimeToShow > 10 Then

nEvents = CType(Math.Min((nTimeToShow / 10), Me._bmpBackground.Height), Integer) Me._iShowEvents = CType(nTimeToShow / nEvents, Integer) Me._iIncrementShow = CType(Me._bmpBackground.Height / nEvents, Integer) Else Me._iShowEvents = 10 Me._iIncrementShow = Me._bmpBackground.Height End If ' We calculate the pixel increment and the timer value for the hiding animation If nTimeToHide > 10 Then nEvents = CType(Math.Min((nTimeToHide / 10), Me._bmpBackground.Height), Integer) Me._iHideEvents = CType(nTimeToHide / nEvents, Integer) Me._iIncrementHide = CType(Me._bmpBackground.Height / nEvents, Integer) Else Me._iHideEvents = 10 Me._iIncrementHide = Me._bmpBackground.Height End If Select Case Me._eWindowState Case TaskbarStates.Hidden Me._eWindowState = TaskbarStates.Appearing SetBounds(Me._rectWorkArea.Right - Me._bmpBackground.Width - 17, _ Me._rectWorkArea.Bottom - 1, _ Me._bmpBackground.Width, 0) Me._tmrAnimation.Interval = Me._iShowEvents Me._tmrAnimation.Start() 'We Show the popup without stealing focus ShowWindow(Me.Handle, 4) Case TaskbarStates.Appearing Refresh() Case TaskbarStates.Visible Me._tmrAnimation.Stop() Me._tmrAnimation.Interval = Me._iVisibleEvents Me._tmrAnimation.Start() Refresh() Case TaskbarStates.Disappearing Me._tmrAnimation.Stop() Me._eWindowState = TaskbarStates.Visible SetBounds(Me._rectWorkArea.Right - Me._bmpBackground.Width - 17, _ Me._rectWorkArea.Bottom - Me._bmpBackground.Height - 1, _ Me._bmpBackground.Width, Me._bmpBackground.Height) Me._tmrAnimation.Interval = Me._iVisibleEvents Me._tmrAnimation.Start() Refresh()

End Select End Sub '##SUMMARY Hides the popup Public Shadows Sub Hide() If Me._eWindowState <> TaskbarStates.Hidden Then Me._tmrAnimation.Stop() Me._eWindowState = TaskbarStates.Hidden MyBase.Hide() End If End Sub '##SUMMARY Sets the background bitmap and its transparency color. '##PARAM strFilename Path of the Background Bitmap on the disk. '##PARAM transparencyColor Color of the Bitmap which won't be visible. Public Sub SetBackgroundBitmap(ByVal strFilename As String, ByVal transparencyColor As Color) Me._bmpBackground = New Bitmap(strFilename) Width = Me._bmpBackground.Width Height = Me._bmpBackground.Height Region = BitmapToRegion(Me._bmpBackground, transparencyColor) End Sub '##SUMMARY Sets the background bitmap and its transparency color. '##PARAM image Image/Bitmap object which represents the Background Bitmap. '##PARAM transparencyColor Color of the Bitmap which won't be visible. Public Sub SetBackgroundBitmap(ByVal image As Image, ByVal transparencyColor As Color) Me._bmpBackground = New Bitmap(image) Width = Me._bmpBackground.Width Height = Me._bmpBackground.Height Region = BitmapToRegion(Me._bmpBackground, transparencyColor) End Sub '##SUMMARY Sets the 3-State Close Button bitmap, its transparency color and its coordinates. '##PARAM strFilename Path of the 3-state Close button Bitmap on the disk (width must a multiple of 3). '##PARAM transparencyColor Color of the Bitmap which won't be visible. '##PARAM position Location of the close button on the popup. Public Sub SetCloseBitmap(ByVal strFilename As String, ByVal transparencyColor As Color, ByVal position As Point) Me._bmpCloseButton = New Bitmap(strFilename) Me._bmpCloseButton.MakeTransparent(transparencyColor) Me._sizCloseButtonSize = New Size(CType(Me._bmpCloseButton.Width / 3, Integer), Me._bmpCloseButton.Height) Me._ptCloseButtonLocation = position End Sub '##SUMMARY Sets the 3-State Close Button bitmap, its transparency color and its coordinates. '##PARAM image Image/Bitmap object which represents the 3-state Close button Bitmap (width must be a multiple of 3).

'##PARAM transparencyColor Color of the Bitmap which won't be visible. '##PARAM position Location of the close button on the popup. Public Sub SetCloseBitmap(ByVal image As Image, ByVal transparencyColor As Color, ByVal position As Point) Me._bmpCloseButton = New Bitmap(image) Me._bmpCloseButton.MakeTransparent(transparencyColor) Me._sizCloseButtonSize = New Size(CType(Me._bmpCloseButton.Width / 3, Integer), Me._bmpCloseButton.Height) Me._ptCloseButtonLocation = position End Sub #End Region #Region "Protected Methods" '##SUMMARY Draws the CloseButton based on the inner state. Protected Sub DrawCloseButton(ByVal grfx As Graphics) If Me._bmpCloseButton Is Nothing Then Exit Sub Dim rectDest As Rectangle = New Rectangle(Me._ptCloseButtonLocation, Me._sizCloseButtonSize) Dim rectSrc As Rectangle If Me._bMouseOverClose Then If Me._bMouseDown Then rectSrc = New Rectangle(New Point(Me._sizCloseButtonSize.Width * 2, 0), Me._sizCloseButtonSize) Else rectSrc = New Rectangle(New Point(Me._sizCloseButtonSize.Width, 0), Me._sizCloseButtonSize) End If Else rectSrc = New Rectangle(New Point(0, 0), Me._sizCloseButtonSize) End If grfx.DrawImage(Me._bmpCloseButton, rectDest, rectSrc, GraphicsUnit.Pixel) End Sub '##SUMMARY Draws the Title and Text content of the TaskNotifier popup window. Protected Sub DrawText(ByVal grfx As Graphics) 'Draw the Title Text If (Not Me._sTitle Is Nothing) AndAlso (Me._sTitle.Length > 0) Then Dim sf As New StringFormat sf.Alignment = StringAlignment.Near sf.LineAlignment = StringAlignment.Center sf.FormatFlags = StringFormatFlags.NoWrap sf.Trimming = StringTrimming.EllipsisCharacter

If Me._bMouseOverTitle Then grfx.DrawString(Me._sTitle, Me._fntTitleHover, New SolidBrush(Me._colTitleHover), _ RectangleF.op_Implicit(Me._rectTitle), sf) Else

grfx.DrawString(Me._sTitle, Me._fntTitleNormal, New SolidBrush(Me._colTitleNormal), _ RectangleF.op_Implicit(Me._rectTitle), sf) End If End If 'Draw the content Text If (Not Me._sText Is Nothing) AndAlso (Me._sText.Length > 0) Then Dim sf As New StringFormat sf.Alignment = StringAlignment.Center sf.LineAlignment = StringAlignment.Center sf.FormatFlags = StringFormatFlags.MeasureTrailingSpaces sf.Trimming = StringTrimming.EllipsisWord If Me._bMouseOverText Then grfx.DrawString(Me._sText, Me._fntTextHover, New SolidBrush(Me._colTextHover), _ RectangleF.op_Implicit(Me._rectText), sf) If Me._bDrawFocusRect Then Me.DrawFocusRectangle(grfx) End If Else grfx.DrawString(Me._sText, Me._fntTextNormal, New SolidBrush(Me._colTextNormal), _ RectangleF.op_Implicit(Me._rectText), sf) End If End If End Sub Protected Sub DrawFocusRectangle(ByVal grfx As Graphics) If Me._bDrawFocusRect Then Dim iBorderWidth As Integer = 1 ControlPaint.DrawBorder(grfx, Me._rectRealText, _ Me._colFocusRect, iBorderWidth, Me._eFocusRectStyle, _ Me._colFocusRect, iBorderWidth, Me._eFocusRectStyle, _ Me._colFocusRect, iBorderWidth, Me._eFocusRectStyle, _ Me._colFocusRect, iBorderWidth, Me._eFocusRectStyle) ' This was the Original Code 'ControlPaint.DrawBorder3D(grfx, Me._rectRealText, Border3DStyle.Flat, _ ' Border3DSide.Top Or Border3DSide.Bottom Or _ ' Border3DSide.Left Or Border3DSide.Right) End If End Sub Protected Sub CalculateMouseRectangles() Dim grfx As Graphics = CreateGraphics() Dim sf As New StringFormat

sf.Alignment = StringAlignment.Center sf.LineAlignment = StringAlignment.Center sf.FormatFlags = StringFormatFlags.MeasureTrailingSpaces Dim sizfTitle As SizeF = _ grfx.MeasureString(Me._sTitle, Me._fntTitleHover, Me._rectTitle.Width, sf) Dim sizfText As SizeF = _ grfx.MeasureString(Me._sText, Me._fntTextHover, Me._rectText.Width, sf) grfx.Dispose() 'We should check if the title size really fits inside the pre-defined title rectangle If sizfTitle.Height > Me._rectTitle.Height Then Me._rectRealTitle = _ New Rectangle(Me._rectTitle.Left, _ Me._rectTitle.Top, _ Me._rectTitle.Width, _ Me._rectTitle.Height) Else Me._rectRealTitle = _ New Rectangle(Me._rectTitle.Left, _ Me._rectTitle.Top, _ CType(sizfTitle.Width, Integer), _ CType(sizfTitle.Height, Integer)) End If Me._rectRealTitle.Inflate(0, 2) 'We should check if the text size really fits inside the pre-defined text rectangle If sizfText.Height > Me._rectText.Height Then Me._rectRealText = _ New Rectangle(CType((_rectText.Width - sizfText.Width) / 2 + _rectText.Left, Integer), _ Me._rectText.Top, _ CType(sizfText.Width, Integer), _ Me._rectText.Height) Else Me._rectRealText = _ New Rectangle(CType((_rectText.Width - sizfText.Width) / 2 + _rectText.Left, Integer), _ CType((_rectText.Height - sizfText.Height) / 2 + _rectText.Top, Integer), _ CType(sizfText.Width, Integer), _ CType(sizfText.Height, Integer)) End If Me._rectRealText.Inflate(0, 2) End Sub Protected Function BitmapToRegion(ByVal bitmap As Bitmap, ByVal transparencyColor As Color) As Region If bitmap Is Nothing Then Throw New ArgumentNullException("Bitmap", "Bitmap cannot be Nothing!") End If

Dim height As Integer = bitmap.Height Dim width As Integer = bitmap.Width Dim path As New GraphicsPath Dim i As Integer Dim j As Integer For j = 0 To (height - 1) For i = 0 To (width - 1) If Not bitmap.GetPixel(i, j).Equals(transparencyColor) Then Dim x0 As Integer = i Do While ((i < width) AndAlso (Not bitmap.GetPixel(i, j).Equals(transparencyColor))) i += 1 Loop path.AddRectangle(New Rectangle(x0, j, i - x0, 1)) End If Next Next Dim region As New Region(path) path.Dispose() Return region End Function #End Region #Region "OnTimer Event Handler" Protected Sub OnTimer(ByVal sender As Object, ByVal e As EventArgs) Select Case Me._eWindowState Case TaskbarStates.Appearing If Height < Me._bmpBackground.Height Then SetBounds(Left, Top - Me._iIncrementShow, Width, Height + Me._iIncrementShow) Else Me._tmrAnimation.Stop() Height = Me._bmpBackground.Height Me._tmrAnimation.Interval = Me._iVisibleEvents Me._eWindowState = TaskbarStates.Visible Me._tmrAnimation.Start() End If Case TaskbarStates.Visible Me._tmrAnimation.Stop() Me._tmrAnimation.Interval = Me._iHideEvents ' Rev 002 If ((Me._bKeepVisibleOnMouseOver) AndAlso (Not Me._bMouseOverPopup)) OrElse _ (Not Me._bKeepVisibleOnMouseOver) Then

Me._eWindowState = TaskbarStates.Disappearing End If Me._tmrAnimation.Start() Case TaskbarStates.Disappearing ' Rev 002 If (Me._bReShowOnMouseOver) AndAlso (Me._bMouseOverPopup) Then Me._eWindowState = TaskbarStates.Appearing Else If Top < Me._rectWorkArea.Bottom Then SetBounds(Left, Top + Me._iIncrementHide, Width, Height Me._iIncrementHide) Else Hide() End If End If End Select End Sub #End Region #Region "Overriden Base Class Methods" Protected Overrides Sub OnMouseEnter(ByVal e As EventArgs) MyBase.OnMouseEnter(e) Me._bMouseOverPopup = True Refresh() End Sub Protected Overrides Sub OnMouseLeave(ByVal e As EventArgs) MyBase.OnMouseLeave(e) Me._bMouseOverPopup = False Me._bMouseOverClose = False Me._bMouseOverTitle = False Me._bMouseOverText = False Refresh() End Sub Protected Overrides Sub OnMouseMove(ByVal e As MouseEventArgs) MyBase.OnMouseMove(e) Dim bContentModified As Boolean = False If ((e.X > Me._ptCloseButtonLocation.X) (e.X < (Me._ptCloseButtonLocation.X AndAlso _ (e.Y > Me._ptCloseButtonLocation.Y) (e.Y < (Me._ptCloseButtonLocation.Y AndAlso _ Me._bCloseButtonClickEnabled) Then If Not Me._bMouseOverClose Then Me._bMouseOverClose = True Me._bMouseOverTitle = False Me._bMouseOverText = False Cursor = Cursors.Hand bContentModified = True AndAlso _ + Me._sizCloseButtonSize.Width)) AndAlso _ + Me._sizCloseButtonSize.Height))

End If Else If Me._rectRealText.Contains(New Point(e.X, e.Y)) AndAlso Me._bTextClickEnabled Then If Not Me._bMouseOverText Then Me._bMouseOverClose = False Me._bMouseOverTitle = False Me._bMouseOverText = True Cursor = Cursors.Hand bContentModified = True End If Else If Me._rectRealTitle.Contains(New Point(e.X, e.Y)) AndAlso Me._bTitleClickEnabled Then If Not Me._bMouseOverTitle Then Me._bMouseOverClose = False Me._bMouseOverTitle = True Me._bMouseOverText = False Cursor = Cursors.Hand bContentModified = True End If Else If Me._bMouseOverClose OrElse Me._bMouseOverTitle OrElse Me._bMouseOverText Then _ bContentModified = True Me._bMouseOverClose = False Me._bMouseOverTitle = False Me._bMouseOverText = False Cursor = Cursors.Default End If End If End If If bContentModified Then Refresh() End Sub Protected Overrides Sub OnMouseDown(ByVal e As MouseEventArgs) MyBase.OnMouseDown(e) Me._bMouseDown = True If Me._bMouseOverClose Then Refresh() End Sub Protected Overrides Sub OnMouseUp(ByVal e As MouseEventArgs) MyBase.OnMouseUp(e) Me._bMouseDown = False

If Me._bMouseOverClose Then Hide() If Me._bCloseButtonClickEnabled Then _ RaiseEvent CloseButtonClick(Me, New EventArgs) Else If Me._bMouseOverTitle Then If Me._bTitleClickEnabled Then _ RaiseEvent TitleClick(Me, New EventArgs) Else If Me._bMouseOverText Then If Me._bTextClickEnabled Then _ RaiseEvent TextClick(Me, New EventArgs) End If End If End If End Sub Protected Overrides Sub OnPaintBackground(ByVal e As PaintEventArgs) Dim grfx As Graphics = e.Graphics grfx.PageUnit = GraphicsUnit.Pixel Dim offScreenGraphics As Graphics Dim offScreenBitmap As Bitmap offScreenBitmap = New Bitmap(Me._bmpBackground.Width, Me._bmpBackground.Height) offScreenGraphics = Graphics.FromImage(offScreenBitmap) If Not Me._bmpBackground Is Nothing Then offScreenGraphics.DrawImage(Me._bmpBackground, 0, 0, _ Me._bmpBackground.Width, _ Me._bmpBackground.Height) End If DrawCloseButton(offScreenGraphics) DrawText(offScreenGraphics) grfx.DrawImage(offScreenBitmap, 0, 0) End Sub #End Region

Private Sub InitializeComponent() Me.SuspendLayout() '

'TaskBarNotifier ' Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13) Me.ClientSize = New System.Drawing.Size(288, 182) Me.Name = "TaskBarNotifier" Me.ResumeLayout(False) End Sub Private Sub TaskBarNotifier_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load End Sub End Class

WindowsControler.vb ( Classe)
' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' WindowsController class for VB.NET Version: 1.1 Copyright 2002-2003, The KPD-Team All rights reserved. http://www.mentalis.org/ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Neither the name of the KPD-Team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Imports Imports Imports Imports Imports

System System.Text System.Diagnostics System.Runtime.InteropServices Microsoft.VisualBasic

'Namespace Org.Mentalis.Utilities '/// <summary> '/// Specifies the type of restart options that an application can use. '/// </summary> Public Enum RestartOptions

'/// <summary> '/// Shuts down all processes running in the security context of the process that called the ExitWindowsEx function. Then it logs the user off. '/// </summary> LogOff = 0 '/// <summary> '/// Shuts down the system and turns off the power. The system must support the power-off feature. '/// </summary> PowerOff = 8 '/// <summary> '/// Shuts down the system and then restarts the system. '/// </summary> Reboot = 2 '/// <summary> '/// Shuts down the system to a point at which it is safe to turn off the power. All file buffers have been flushed to disk, and all running processes have stopped. If the system supports the power-off feature, the power is also turned off. '/// </summary> ShutDown = 1 '/// <summary> '/// Suspends the system. '/// </summary> Suspend = -1 '/// <summary> '/// Hibernates the system. '/// </summary> Hibernate = -2 End Enum '/// <summary> '/// An LUID is a 64-bit value guaranteed to be unique only on the system on which it was generated. The uniqueness of a locally unique identifier (LUID) is guaranteed only until the system is restarted. '/// </summary> <StructLayout(LayoutKind.Sequential, Pack:=1)> _ Friend Structure LUID '/// <summary> '/// The low order part of the 64 bit value. '/// </summary> Public LowPart As Integer '/// <summary> '/// The high order part of the 64 bit value. '/// </summary> Public HighPart As Integer End Structure '/// <summary> '/// The LUID_AND_ATTRIBUTES structure represents a locally unique identifier (LUID) and its attributes. '/// </summary> <StructLayout(LayoutKind.Sequential, Pack:=1)> _ Friend Structure LUID_AND_ATTRIBUTES '/// <summary> '/// Specifies an LUID value. '/// </summary> Public pLuid As LUID '/// <summary> '/// Specifies attributes of the LUID. This value contains up to 32 one-bit flags. Its meaning is dependent on the definition and use of the LUID. '/// </summary> Public Attributes As Integer End Structure

'/// <summary> '/// The TOKEN_PRIVILEGES structure contains information about a set of privileges for an access token. '/// </summary> <StructLayout(LayoutKind.Sequential, Pack:=1)> _ Friend Structure TOKEN_PRIVILEGES '/// <summary> '/// Specifies the number of entries in the Privileges array. '/// </summary> Public PrivilegeCount As Integer '/// <summary> '/// Specifies an array of LUID_AND_ATTRIBUTES structures. Each structure contains the LUID and attributes of a privilege. '/// </summary> Public Privileges As LUID_AND_ATTRIBUTES End Structure '/// <summary> '/// Implements methods to exit Windows. '/// </summary> Public Class WindowsController '/// <summary>Required to enable or disable the privileges in an access token.</summary> Private Const TOKEN_ADJUST_PRIVILEGES As Integer = &H20 '/// <summary>Required to query an access token.</summary> Private Const TOKEN_QUERY As Integer = &H8 '/// <summary>The privilege is enabled.</summary> Private Const SE_PRIVILEGE_ENABLED As Integer = &H2 '/// <summary>Specifies that the function should search the system messagetable resource(s) for the requested message.</summary> Private Const FORMAT_MESSAGE_FROM_SYSTEM As Integer = &H1000 '/// <summary>Forces processes to terminate. When this flag is set, the system does not send the WM_QUERYENDSESSION and WM_ENDSESSION messages. This can cause the applications to lose data. Therefore, you should only use this flag in an emergency.</summary> Private Const EWX_FORCE As Integer = 4 '/// <summary> '/// The LoadLibrary function maps the specified executable module into the address space of the calling process. '/// </summary> '/// <param name="lpLibFileName">Pointer to a null-terminated string that names the executable module (either a .dll or .exe file). The name specified is the file name of the module and is not related to the name stored in the library module itself, as specified by the LIBRARY keyword in the module-definition (.def) file.</param> '/// <returns>If the function succeeds, the return value is a handle to the module.<br></br><br>If the function fails, the return value is NULL. To get extended error information, call Marshal.GetLastWin32Error.</br></returns> Private Declare Ansi Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" (ByVal lpLibFileName As String) As IntPtr '/// <summary> '/// The FreeLibrary function decrements the reference count of the loaded dynamic-link library (DLL). When the reference count reaches zero, the module is unmapped from the address space of the calling process and the handle is no longer valid. '/// </summary> '/// <param name="hLibModule">Handle to the loaded DLL module. The LoadLibrary or GetModuleHandle function returns this handle.</param> '/// <returns>If the function succeeds, the return value is nonzero.<br></br><br>If the function fails, the return value is zero. To get extended error information, call Marshal.GetLastWin32Error.</br></returns> Private Declare Ansi Function FreeLibrary Lib "kernel32" (ByVal hLibModule As IntPtr) As Integer

'/// <summary> '/// The GetProcAddress function retrieves the address of an exported function or variable from the specified dynamic-link library (DLL). '/// </summary> '/// <param name="hModule">Handle to the DLL module that contains the function or variable. The LoadLibrary or GetModuleHandle function returns this handle.</param> '/// <param name="lpProcName">Pointer to a null-terminated string containing the function or variable name, or the function's ordinal value. If this parameter is an ordinal value, it must be in the low-order word; the high-order word must be zero.</param> '/// <returns>If the function succeeds, the return value is the address of the exported function or variable.<br></br><br>If the function fails, the return value is NULL. To get extended error information, call Marshal.GetLastWin32Error.</br></returns> Private Declare Ansi Function GetProcAddress Lib "kernel32" (ByVal hModule As IntPtr, ByVal lpProcName As String) As IntPtr '/// <summary> '/// The SetSuspendState function suspends the system by shutting power down. Depending on the Hibernate parameter, the system either enters a suspend (sleep) state or hibernation (S4). If the ForceFlag parameter is TRUE, the system suspends operation immediately; if it is FALSE, the system requests permission from all applications and device drivers before doing so. '/// </summary> '/// <param name="Hibernate">Specifies the state of the system. If TRUE, the system hibernates. If FALSE, the system is suspended.</param> '/// <param name="ForceCritical">Forced suspension. If TRUE, the function broadcasts a PBT_APMSUSPEND event to each application and driver, then immediately suspends operation. If FALSE, the function broadcasts a PBT_APMQUERYSUSPEND event to each application to request permission to suspend operation.</param> '/// <param name="DisableWakeEvent">If TRUE, the system disables all wake events. If FALSE, any system wake events remain enabled.</param> '/// <returns>If the function succeeds, the return value is nonzero.<br></br><br>If the function fails, the return value is zero. To get extended error information, call Marshal.GetLastWin32Error.</br></returns> Private Declare Ansi Function SetSuspendState Lib "powrprof" (ByVal Hibernate As Integer, ByVal ForceCritical As Integer, ByVal DisableWakeEvent As Integer) As Integer '/// <summary> '/// The OpenProcessToken function opens the access token associated with a process. '/// </summary> '/// <param name="ProcessHandle">Handle to the process whose access token is opened.</param> '/// <param name="DesiredAccess">Specifies an access mask that specifies the requested types of access to the access token. These requested access types are compared with the token's discretionary access-control list (DACL) to determine which accesses are granted or denied.</param> '/// <param name="TokenHandle">Pointer to a handle identifying the newlyopened access token when the function returns.</param> '/// <returns>If the function succeeds, the return value is nonzero.<br></br><br>If the function fails, the return value is zero. To get extended error information, call Marshal.GetLastWin32Error.</br></returns> Private Declare Ansi Function OpenProcessToken Lib "advapi32" (ByVal ProcessHandle As IntPtr, ByVal DesiredAccess As Integer, ByRef TokenHandle As IntPtr) As Integer '/// <summary> '/// The LookupPrivilegeValue function retrieves the locally unique identifier (LUID) used on a specified system to locally represent the specified privilege name. '/// </summary>

'/// <param name="lpSystemName">Pointer to a null-terminated string specifying the name of the system on which the privilege name is looked up. If a null string is specified, the function attempts to find the privilege name on the local system.</param> '/// <param name="lpName">Pointer to a null-terminated string that specifies the name of the privilege, as defined in the Winnt.h header file. For example, this parameter could specify the constant SE_SECURITY_NAME, or its corresponding string, "SeSecurityPrivilege".</param> '/// <param name="lpLuid">Pointer to a variable that receives the locally unique identifier by which the privilege is known on the system, specified by the lpSystemName parameter.</param> '/// <returns>If the function succeeds, the return value is nonzero.<br></br><br>If the function fails, the return value is zero. To get extended error information, call Marshal.GetLastWin32Error.</br></returns> Private Declare Ansi Function LookupPrivilegeValue Lib "advapi32" Alias "LookupPrivilegeValueA" (ByVal lpSystemName As String, ByVal lpName As String, ByRef lpLuid As LUID) As Integer '/// <summary> '/// The AdjustTokenPrivileges function enables or disables privileges in the specified access token. Enabling or disabling privileges in an access token requires TOKEN_ADJUST_PRIVILEGES access. '/// </summary> '/// <param name="TokenHandle">Handle to the access token that contains the privileges to be modified. The handle must have TOKEN_ADJUST_PRIVILEGES access to the token. If the PreviousState parameter is not NULL, the handle must also have TOKEN_QUERY access.</param> '/// <param name="DisableAllPrivileges">Specifies whether the function disables all of the token's privileges. If this value is TRUE, the function disables all privileges and ignores the NewState parameter. If it is FALSE, the function modifies privileges based on the information pointed to by the NewState parameter.</param> '/// <param name="NewState">Pointer to a TOKEN_PRIVILEGES structure that specifies an array of privileges and their attributes. If the DisableAllPrivileges parameter is FALSE, AdjustTokenPrivileges enables or disables these privileges for the token. If you set the SE_PRIVILEGE_ENABLED attribute for a privilege, the function enables that privilege; otherwise, it disables the privilege. If DisableAllPrivileges is TRUE, the function ignores this parameter.</param> '/// <param name="BufferLength">Specifies the size, in bytes, of the buffer pointed to by the PreviousState parameter. This parameter can be zero if the PreviousState parameter is NULL.</param> '/// <param name="PreviousState">Pointer to a buffer that the function fills with a TOKEN_PRIVILEGES structure that contains the previous state of any privileges that the function modifies. This parameter can be NULL.</param> '/// <param name="ReturnLength">Pointer to a variable that receives the required size, in bytes, of the buffer pointed to by the PreviousState parameter. This parameter can be NULL if PreviousState is NULL.</param> '/// <returns>If the function succeeds, the return value is nonzero. To determine whether the function adjusted all of the specified privileges, call Marshal.GetLastWin32Error.</returns> Private Declare Ansi Function AdjustTokenPrivileges Lib "advapi32" (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 '/// <summary> '/// The ExitWindowsEx function either logs off the current user, shuts down the system, or shuts down and restarts the system. It sends the WM_QUERYENDSESSION message to all applications to determine if they can be terminated. '/// </summary> '/// <param name="uFlags">Specifies the type of shutdown.</param> '/// <param name="dwReserved">This parameter is ignored.</param>

'/// <returns>If the function succeeds, the return value is nonzero.<br></br><br>If the function fails, the return value is zero. To get extended error information, call Marshal.GetLastWin32Error.</br></returns> Private Declare Ansi Function ExitWindowsEx Lib "user32" (ByVal uFlags As Integer, ByVal dwReserved As Integer) As Integer '/// <summary> '/// The FormatMessage function formats a message string. The function requires a message definition as input. The message definition can come from a buffer passed into the function. It can come from a message table resource in an already-loaded module. Or the caller can ask the function to search the system's message table resource(s) for the message definition. The function finds the message definition in a message table resource based on a message identifier and a language identifier. The function copies the formatted message text to an output buffer, processing any embedded insert sequences if requested. '/// </summary> '/// <param name="dwFlags">Specifies aspects of the formatting process and how to interpret the lpSource parameter. The low-order byte of dwFlags specifies how the function handles line breaks in the output buffer. The low-order byte can also specify the maximum width of a formatted output line.</param> '/// <param name="lpSource">Specifies the location of the message definition. The type of this parameter depends upon the settings in the dwFlags parameter.</param> '/// <param name="dwMessageId">Specifies the message identifier for the requested message. This parameter is ignored if dwFlags includes FORMAT_MESSAGE_FROM_STRING.</param> '/// <param name="dwLanguageId">Specifies the language identifier for the requested message. This parameter is ignored if dwFlags includes FORMAT_MESSAGE_FROM_STRING.</param> '/// <param name="lpBuffer">Pointer to a buffer for the formatted (and nullterminated) message. If dwFlags includes FORMAT_MESSAGE_ALLOCATE_BUFFER, the function allocates a buffer using the LocalAlloc function, and places the pointer to the buffer at the address specified in lpBuffer.</param> '/// <param name="nSize">If the FORMAT_MESSAGE_ALLOCATE_BUFFER flag is not set, this parameter specifies the maximum number of TCHARs that can be stored in the output buffer. If FORMAT_MESSAGE_ALLOCATE_BUFFER is set, this parameter specifies the minimum number of TCHARs to allocate for an output buffer. For ANSI text, this is the number of bytes; for Unicode text, this is the number of characters.</param> '/// <param name="Arguments">Pointer to an array of values that are used as insert values in the formatted message. A %1 in the format string indicates the first value in the Arguments array; a %2 indicates the second argument; and so on.</param> '/// <returns>If the function succeeds, the return value is the number of TCHARs stored in the output buffer, excluding the terminating null character.<br></br><br>If the function fails, the return value is zero. To get extended error information, call Marshal.GetLastWin32Error.</br></returns> Private Declare Ansi 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 '/// <summary> '/// Exits windows (and tries to enable any required access rights, if necesarry). '/// </summary> '/// <param name="how">One of the RestartOptions values that specifies how to exit windows.</param> '/// <param name="force">True if the exit has to be forced, false otherwise.</param> '/// <exception cref="PrivilegeException">There was an error while requesting a required privilege.</exception> '/// <exception cref="PlatformNotSupportedException">The requested exit method is not supported on this platform.</exception>

Public Shared 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 Else ExitWindows(CType(how, Integer), force) End Select End Sub '/// <summary> '/// Exits windows (and tries to enable any required access rights, if necesarry). '/// </summary> '/// <param name="how">One of the RestartOptions values that specifies how to exit windows.</param> '/// <param name="force">True if the exit has to be forced, false otherwise.</param> '/// <remarks>This method cannot hibernate or suspend the system.</remarks> '/// <exception cref="PrivilegeException">There was an error while requesting a required privilege.</exception> Protected Shared 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 '/// <summary> '/// Tries to enable the specified privilege. '/// </summary> '/// <param name="privilege">The privilege to enable.</param> '/// <exception cref="PrivilegeException">There was an error while requesting a required privilege.</exception> '/// <remarks>Thanks to Michael S. Muegel for notifying us about a bug in this code.</remarks> Protected Shared Sub EnableToken(ByVal privilege As String) If (Environment.OSVersion.Platform <> PlatformID.Win32NT) OrElse (Not CheckEntryPoint("advapi32.dll", "AdjustTokenPrivileges")) Then Return Dim tokenHandle As IntPtr Dim privilegeLUID As LUID Dim newPrivileges As 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 If AdjustTokenPrivileges(tokenHandle, 0, tokenPrivileges, 4 + (12 * tokenPrivileges.PrivilegeCount), newPrivileges, 4 + (12 * newPrivileges.PrivilegeCount)) = 0 Then Throw New PrivilegeException(FormatError(Marshal.GetLastWin32Error)) End Sub '/// <summary> '/// Suspends or hibernates the system. '/// </summary> '/// <param name="hibernate">True if the system has to hibernate, false if the system has to be suspended.</param>

'/// <param name="force">True if the exit has to be forced, false otherwise.</param> '/// <exception cref="PlatformNotSupportedException">The requested exit method is not supported on this platform.</exception> Protected Shared 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(CType(IIf(hibernate, 1, 0), Integer), CType(IIf(force, 1, 0), Integer), 0) End Sub '/// <summary> '/// Checks whether a specified method exists on the local computer. '/// </summary> '/// <param name="library">The library that holds the method.</param> '/// <param name="method">The entry point of the requested method.</param> '/// <returns>True if the specified method is present, false otherwise.</returns> Protected Shared 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 '/// <summary> '/// Formats an error number into an error message. '/// </summary> '/// <param name="number">The error number to convert.</param> '/// <returns>A string representation of the specified error number.</returns> Protected Shared Function FormatError(ByVal number As Integer) As String Try Dim buffer As New StringBuilder(255) FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, IntPtr.Zero, number, 0, buffer, buffer.Capacity, 0) Return buffer.ToString() Catch e As Exception Return "Unspecified error [" + number.ToString() + "]" End Try End Function End Class '/// <summary> '/// The exception that is thrown when an error occures when requesting a specific privilege. '/// </summary> Public Class PrivilegeException Inherits Exception '/// <summary> '/// Initializes a new instance of the PrivilegeException class. '/// </summary> Public Sub New() MyBase.New() End Sub '/// <summary>

'/// Initializes a new instance of the PrivilegeException class with a specified error message. '/// </summary> '/// <param name="message">The message that describes the error.</param> Public Sub New(ByVal message As String) MyBase.New(message) End Sub End Class 'End Namespace

You might also like