Browse Source

дописываем сервисные функции

master
cyrax 6 years ago
parent
commit
61eb41af1e
  1. 139
      LVNC-RS/LVNC-RS-Svc.vb
  2. 3
      LVNC-RS/LVNC-RS.vbproj
  3. 72
      LVNC-RS/My Project/Settings.Designer.vb
  4. 10
      LVNC-RS/app.config
  5. 17
      LVNC-RS/frmLVNC-RS-Main.vb

139
LVNC-RS/LVNC-RS-Svc.vb

@ -32,11 +32,22 @@
' 2 = Покси недоступен. ' 2 = Покси недоступен.
Public bProxyStatus As Byte = 0 Public bProxyStatus As Byte = 0
' Режим и права доступа
' Возможны следующие значения:
' 0 = Неопределённое состояние (при старте приложения);
' 1 = От имени обычного пользователя. VNC еще не запущен;
' 2 = От имени обычного пользователя. VNC работает в режиме приложения;
' 3 = От имени обычного пользователя. VNC работает как служба;
' 4 = От имени администратора. VNC еще не запущен;
' 5 = От имени администратора. VNC работает как служба;
Public bExecMode As Byte = 0
' Настройки приложения ' Настройки приложения
Private oConfigFile As New IniFile Private oConfigFile As New IniFile
' Процесс winvnc.exe ' Процесс winvnc.exe
Private VNCProc As Process = Nothing Private VNCProc As Process = Nothing
Private sVNCServiceName As String = "uvnc_service"
''' <summary> ''' <summary>
''' Инициализация приложения ''' Инициализация приложения
@ -64,6 +75,8 @@
If sProxyHost.Length = 0 Or sProxyPort.Length = 0 Then Return False If sProxyHost.Length = 0 Or sProxyPort.Length = 0 Then Return False
bExecMode = GetExecutionMode()
' Генерируем ID и пароль ' Генерируем ID и пароль
sSupportID = GetSupportID() sSupportID = GetSupportID()
sSupportPasswd = GetSupportPasswd() sSupportPasswd = GetSupportPasswd()
@ -131,14 +144,28 @@
Return False Return False
End Try End Try
AddHandler VNCProc.Exited, AddressOf VNCProcessExited
Return True Return True
End Function End Function
Public Function StopVNC() As Boolean Public Sub StopVNC()
If VNCProc IsNot Nothing And VNCProc.Id <> 0 Then If VNCProc IsNot Nothing And Not VNCProc.HasExited Then
VNCProc. VNCProc.CloseMainWindow()
VNCProc.WaitForExit(1000)
If Not VNCProc.HasExited Then
VNCProc.Kill()
End If
End If End If
End Function
VNCProc = Nothing
bExecMode =
End Sub
Private Sub VNCProcessExited(ByVal sender As Object, ByVal e As System.EventArgs)
VNCProc.Close()
End Sub
Private Function GetAllUsersDir() As String Private Function GetAllUsersDir() As String
Dim sRegShellPath As String = "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" Dim sRegShellPath As String = "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
@ -246,10 +273,110 @@
Private Function GetSupportPasswd() As String Private Function GetSupportPasswd() As String
' Проверяем наличие сохранённого пароля на случай перезапуска от имени администратора ' Проверяем наличие сохранённого пароля на случай перезапуска от имени администратора
Dim pwd As String = oConfigFile.GetKeyValue("lvnc", "passwd") Dim pwd As String = oConfigFile.GetKeyValue("lvnc", "passwd")
If pwd IsNot Nothing And pwd <> String.Empty Then Return pwd If pwd IsNot Nothing And pwd <> String.Empty Then
If bExecMode = 3 Then
Return pwd
End If
End If
Dim rndGen As New System.Random Dim rndGen As New System.Random
Return (rndGen.Next(1000, 10000).ToString) pwd = rndGen.Next(1000, 10000).ToString
Dim vncSetPasswd As New ProcessStartInfo
With vncSetPasswd
.Arguments = pwd
.FileName = sRunTimeDir & "\UltraVNC\setpasswd.exe"
.UseShellExecute = True
.WindowStyle = ProcessWindowStyle.Hidden
.WorkingDirectory = sRunTimeDir & "\UltraVNC"
End With
Try
Dim p As Process = Process.Start(startInfo)
p.WaitForExit()
Catch ex As System.ComponentModel.Win32Exception
Return String.Empty
End Try
Return pwd
End Function
Private Function GetExecutionMode() As Byte
Dim bMode As Byte = 0
If My.User.IsInRole(ApplicationServices.BuiltInRole.Administrator) Then
bMode = 4
If IsServiceInstalled(sVNCServiceName) Then
If GetServiceStatus(sVNCServiceName) = "running" Then
bMode = 5
End If
End If
Else
bMode = 1
If IsServiceInstalled(sVNCServiceName) Then
If GetServiceStatus(sVNCServiceName) = "running" Then
bMode = 3
End If
Else
If VNCProc Is Nothing Then
For Each p As Process In Process.GetProcesses()
If p.ProcessName.Contains("winvnc") Then
VNCProc = p
End If
Next
If VNCProc IsNot Nothing Then
StopVNC()
End If
Else
bMode = 2
End If
End If
End If
Return bMode
End Function
Private Function IsServiceInstalled(ByVal sServiceName As String) As Boolean
Dim bResult As Boolean = False
Dim oServiceArray() As ServiceProcess.ServiceController = ServiceProcess.ServiceController.GetServices
For Each oServiceController As ServiceProcess.ServiceController In oServiceArray
If oServiceController.ServiceName.Trim.ToUpper = sServiceName.Trim.ToUpper Then
Dim i As New ServiceProcess.ServiceControllerPermissionAttribute(Security.Permissions.SecurityAction.Demand)
Dim d As New ServiceProcess.ServiceControllerPermission
Try
If d.Any Then
d.ToString()
End If
Catch ex As Exception
End Try
bResult = True
Exit For
End If
Next
Return bResult
End Function
Public Function GetServiceStatus(ByVal sServiceName As String) As String
Dim sStatus As String = "NA"
Dim oWinSvc As New ServiceProcess.ServiceController
oWinSvc.ServiceName = sServiceName
Select Case oWinSvc.Status
Case ServiceProcess.ServiceControllerStatus.Stopped
sStatus = "stoped"
Case ServiceProcess.ServiceControllerStatus.Running
sStatus = "running"
End Select
Return sStatus
End Function End Function
End Module End Module

3
LVNC-RS/LVNC-RS.vbproj

@ -28,6 +28,8 @@
<IsWebBootstrapper>false</IsWebBootstrapper> <IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust> <UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled> <BootstrapperEnabled>true</BootstrapperEnabled>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget> <PlatformTarget>AnyCPU</PlatformTarget>
@ -72,6 +74,7 @@
<Reference Include="System.Data" /> <Reference Include="System.Data" />
<Reference Include="System.Deployment" /> <Reference Include="System.Deployment" />
<Reference Include="System.Drawing" /> <Reference Include="System.Drawing" />
<Reference Include="System.ServiceProcess" />
<Reference Include="System.Windows.Forms" /> <Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />

72
LVNC-RS/My Project/Settings.Designer.vb

@ -1,10 +1,10 @@
'------------------------------------------------------------------------------ '------------------------------------------------------------------------------
' <auto-generated> ' <auto-generated>
' This code was generated by a tool. ' Этот код создан программой.
' Runtime Version:4.0.30319.42000 ' Исполняемая версия:4.0.30319.42000
' '
' Changes to this file may cause incorrect behavior and will be lost if ' Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
' the code is regenerated. ' повторной генерации кода.
' </auto-generated> ' </auto-generated>
'------------------------------------------------------------------------------ '------------------------------------------------------------------------------
@ -13,42 +13,42 @@ Option Explicit On
Namespace My Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0"), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.8.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings) Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings)
#Region "My.Settings Auto-Save Functionality" #Region "Функция автоматического сохранения My.Settings"
#If _MyType = "WindowsForms" Then #If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ <Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) Private Shared Sub AutoSaveSettings(sender As Global.System.Object, e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then If My.Application.SaveMySettingsOnExit Then
My.Settings.Save() My.Settings.Save()
End If End If
End Sub End Sub
#End If #End If
#End Region #End Region
Public Shared ReadOnly Property [Default]() As MySettings Public Shared ReadOnly Property [Default]() As MySettings
Get Get
#If _MyType = "WindowsForms" Then #If _MyType = "WindowsForms" Then
If Not addedHandler Then If Not addedHandler Then
SyncLock addedHandlerLockObject SyncLock addedHandlerLockObject
If Not addedHandler Then If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True addedHandler = True
End If End If
End SyncLock End SyncLock
End If End If
#End If #End If
Return defaultInstance Return defaultInstance
End Get End Get
@ -57,13 +57,13 @@ Namespace My
End Namespace End Namespace
Namespace My Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _ <Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _ <Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.LVNC_RS.My.MySettings Friend ReadOnly Property Settings() As Global.LVNC_RS.My.MySettings
Get Get
Return Global.LVNC_RS.My.MySettings.Default Return Global.LVNC_RS.My.MySettings.Default

10
LVNC-RS/app.config

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8" ?> <?xml version="1.0" encoding="utf-8"?>
<configuration> <configuration>
<system.diagnostics> <system.diagnostics>
<sources> <sources>
@ -12,14 +12,12 @@
</source> </source>
</sources> </sources>
<switches> <switches>
<add name="DefaultSwitch" value="Information" /> <add name="DefaultSwitch" value="Information"/>
</switches> </switches>
<sharedListeners> <sharedListeners>
<add name="FileLog" <add name="FileLog" type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" initializeData="FileLogWriter"/>
type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
initializeData="FileLogWriter"/>
<!-- Раскомментируйте следующую секцию и замените APPLICATION_NAME на имя своего приложения для записи в журнал событий приложения --> <!-- Раскомментируйте следующую секцию и замените APPLICATION_NAME на имя своего приложения для записи в журнал событий приложения -->
<!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> --> <!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
</sharedListeners> </sharedListeners>
</system.diagnostics> </system.diagnostics>
</configuration> <startup><supportedRuntime version="v2.0.50727"/></startup></configuration>

17
LVNC-RS/frmLVNC-RS-Main.vb

@ -1,4 +1,6 @@
Public Class frmLVNCRSMain Imports System.ComponentModel
Public Class frmLVNCRSMain
Private Sub frmLVNCRSMain_Load(sender As Object, e As EventArgs) Handles Me.Load Private Sub frmLVNCRSMain_Load(sender As Object, e As EventArgs) Handles Me.Load
txtLVNCSupportID.Text = String.Empty txtLVNCSupportID.Text = String.Empty
txtLVNCSupportPasswd.Text = String.Empty txtLVNCSupportPasswd.Text = String.Empty
@ -16,12 +18,6 @@
Svc.CheckProxy() Svc.CheckProxy()
'If My.User.IsInRole(ApplicationServices.BuiltInRole.Administrator) Then
' tsButtonRunAs.Image = Global.LVNC_RS.My.Resources.is_admin_on
'Else
' tsButtonRunAs.Image = Global.LVNC_RS.My.Resources.is_admin_off
'End If
If Svc.bProxyStatus = 1 Then If Svc.bProxyStatus = 1 Then
tsLabelSrvStatus.Image = My.Resources.online tsLabelSrvStatus.Image = My.Resources.online
txtLVNCSupportID.Text = Format(Convert.ToInt32(Svc.sSupportID), "### ### ##0") txtLVNCSupportID.Text = Format(Convert.ToInt32(Svc.sSupportID), "### ### ##0")
@ -80,6 +76,7 @@
tsLabelSrvStatus.Text = String.Empty tsLabelSrvStatus.Text = String.Empty
txtLVNCSupportID.Text = Format(Convert.ToInt32(Svc.sSupportID), "### ### ##0") txtLVNCSupportID.Text = Format(Convert.ToInt32(Svc.sSupportID), "### ### ##0")
txtLVNCSupportPasswd.Text = Svc.sSupportPasswd txtLVNCSupportPasswd.Text = Svc.sSupportPasswd
Else Else
tsLabelSrvStatus.Image = My.Resources.offline tsLabelSrvStatus.Image = My.Resources.offline
If bProxyOldStatus = 1 Then If bProxyOldStatus = 1 Then
@ -89,4 +86,10 @@
End If End If
End If End If
End Sub End Sub
Private Sub frmLVNCRSMain_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
tsLabelSrvStatus.Text = "Завершение работы..."
Svc.StopVNC()
End Sub
End Class End Class

Loading…
Cancel
Save