Как програмно разорвать соединение

Программирование на Visual Basic, главный форум. Обсуждение тем программирования на VB 1—6.
Даже если вы плохо разбираетесь в VB и программировании вообще — тут вам помогут. В разумных пределах, конечно.
Правила форума
Темы, в которых будет сначала написано «что нужно сделать», а затем просьба «помогите», будут закрыты.
Читайте требования к создаваемым темам.
neprden
Обычный пользователь
Обычный пользователь
 
Сообщения: 64
Зарегистрирован: 04.10.2003 (Сб) 19:37

Как програмно разорвать соединение

Сообщение neprden » 02.12.2003 (Вт) 14:56

Как програмно разорвать соединение под 9х и под ХР, есть ли апшки такие

hCORe
VB - Экстремал
VB - Экстремал
Аватара пользователя
 
Сообщения: 2332
Зарегистрирован: 22.02.2003 (Сб) 15:21
Откуда: parent directory

Api имеется!

Сообщение hCORe » 02.12.2003 (Вт) 18:38

Используй функции:

Код: Выделить всё
Declare Function RasHangUp Lib "rasapi32.dll" Alias "RasHangUpA" (ByVal hRasConn As Long) As Long

Declare Function RasEnumEntries Lib "RasApi32.DLL" Alias "RasEnumEntriesA" (ByVal reserved As String, ByVal lpszPhonebook As String, lprasentryname As Any, lpcb As Long, lpcEntries As Long) As Long


Информацию об ошибке устанавливает GetLastError.

ЗЫ. Только, если честно, я ими никогда не пользовался :evil:, поэтому не знаю "подводных камней" функций и ухищрений при работе с ними. См. APIGuide (http://www.allapi.net)
Моду создают модоки, а распространяют модозвоны.

SSecurity
Служба безопасности
Аватара пользователя
 
Сообщения: 1283
Зарегистрирован: 19.08.2003 (Вт) 1:11
Откуда: Россия, Мурманск

Сообщение SSecurity » 04.12.2003 (Чт) 1:35

Попробуй рестартом :) ... он тогда все и порвет :)) .... кстати от хака защитит тебя рестарт или неисправная вилка телефонной розетки :)
Программист - это маленький Бог, а все его ошибки - это самостоятельные творения:)
Так задумано:)

neprden
Обычный пользователь
Обычный пользователь
 
Сообщения: 64
Зарегистрирован: 04.10.2003 (Сб) 19:37

Как програмно разорвать соединение

Сообщение neprden » 10.12.2003 (Ср) 15:22

Спасибо за совет
Вообще то пишу прогу которая кроме всего прочего
могла бы посылать письма и в конце разрывать соединение
А как програмно сделать Reset ? :D

Amed
Алфизик
Алфизик
 
Сообщения: 5346
Зарегистрирован: 09.03.2003 (Вс) 9:26

Сообщение Amed » 10.12.2003 (Ср) 21:26

API - ExitWindowsEx... Подробнее про синтаксис поищи на форуме - здесь была такая тема...

Кстати, такая функция работает только в Windows 98, для XP нужно делать по-другому, с другой API... Какой точно, - не помню, поищи опять же на форуме или в Яндексе что-то вроде "Выключение компьютера XP"

A.A.Z.
Член-корреспондент академии VBStreets
Член-корреспондент академии VBStreets
 
Сообщения: 3035
Зарегистрирован: 30.06.2003 (Пн) 13:38

Сообщение A.A.Z. » 10.12.2003 (Ср) 22:05

Info: :arrow:
API-Guide писал(а):1)
Description:
The RasHangUp function terminates a remote access connection. The connection is specified with a RAS connection handle. The function releases all RASAPI32.DLL resources associated with the handle.

Declaration:
Код: Выделить всё
Declare Function RasHangUp Lib "rasapi32.dll" Alias "RasHangUpA" (ByVal hRasConn As Long) As Long


Parameters:
· hrasconn
Identifies the remote access connection to terminate. This is a handle returned from a previous call to RasDial or RasEnumConnections.

Return Values:
If the function succeeds, the return value is zero.

If the function fails, the return value is a nonzero error value listed in the RAS header file, or ERROR_INVALID_HANDLE.

Sample:
Код: Выделить всё
Const RAS_MAXENTRYNAME = 256
Const RAS_MAXDEVICETYPE = 16
Const RAS_MAXDEVICENAME = 128
Const RAS_RASCONNSIZE = 412
Private Type RasConn
    dwSize As Long
    hRasConn As Long
    szEntryName(RAS_MAXENTRYNAME) As Byte
    szDeviceType(RAS_MAXDEVICETYPE) As Byte
    szDeviceName(RAS_MAXDEVICENAME) As Byte
End Type
Private Declare Function RasEnumConnections Lib "rasapi32.dll" Alias "RasEnumConnectionsA" (lpRasConn As Any, lpcb As Long, lpcConnections As Long) As Long
Private Declare Function RasHangUp Lib "rasapi32.dll" Alias "RasHangUpA" (ByVal hRasConn As Long) As Long
Private Sub Form_Load()
    'KPD-Team 1998
    'URL: http://www.allapi.net/
    'E-Mail: KPDTeam@Allapi.net
    'This program will close your Internet-connection, so to test this, you will have to open an Internet-connection.
    Dim i As Long, lpRasConn(255) As RasConn, lpcb As Long
    Dim lpcConnections As Long, hRasConn As Long
    'Set the structure's size
    lpRasConn(0).dwSize = RAS_RASCONNSIZE
    lpcb = RAS_MAXENTRYNAME * lpRasConn(0).dwSize
    lpcConnections = 0
    'Enumerate all the available connections
    returncode = RasEnumConnections(lpRasConn(0), lpcb, lpcConnections)

    If returncode = 0 Then
        For i = 0 To lpcConnections - 1
            hRasConn = lpRasConn(i).hRasConn
            'Hang up
            returncode = RasHangUp(ByVal hRasConn)
        Next i
    End If
End Sub


2)
Description:
The RasEnumEntries function lists all entry names in a remote access phone book.

Declaration:
Код: Выделить всё
Declare Function RasEnumEntries Lib "RasApi32.DLL" Alias "RasEnumEntriesA" (ByVal reserved As String, ByVal lpszPhonebook As String, lprasentryname As Any, lpcb As Long, lpcEntries As Long) As Long


Parameters:
.reserved
Reserved; must be NULL.

· lpszPhonebook
Windows NT: Pointer to a null-terminated string that specifies the full path and filename of a phone-book (.PBK) file. If this parameter is NULL, the function uses the current default phone-book file. The default phone-book file is the one selected by the user in the User Preferences property sheet of the Dial-Up Networking dialog box.
Windows 95: This parameter is ignored. Dial-up networking stores phone-book entries in the registry rather than in a phone-book file.

· lprasentryname
Points to a buffer that receives an array of RASENTRYNAME structures, one for each phone-book entry. Before calling the function, an application must set the dwSize member of the first RASENTRYNAME structure in the buffer to sizeof(RASENTRYNAME) in order to identify the version of the structure being passed.

· lpcb
Points to a variable that contains the size, in bytes, of the buffer specified by lprasentryname. On return, the function sets this variable to the number of bytes required to successfully complete the call.

· lpcEntries
Points to a variable that the function, if successful, sets to the number of phone-book entries written to the buffer specified by lprasentryname.

Return Values:
If the function succeeds, the return value is zero.

If the function fails, the return value is a nonzero error value listed in the RAS header file or one of ERROR_BUFFER_TOO_SMALL or ERROR_NOT_ENOUGH_MEMORY.

Sample:
Код: Выделить всё
Const RAS95_MaxEntryName = 256
Private Type RASENTRYNAME95
    dwSize As Long
    szEntryName(RAS95_MaxEntryName) As Byte
End Type
Private Declare Function RasEnumEntries Lib "RasApi32.DLL" Alias "RasEnumEntriesA" (ByVal reserved As String, ByVal lpszPhonebook As String, lprasentryname As Any, lpcb As Long, lpcEntries As Long) As Long
Private Sub Form_Load()
    'KPD-Team 1999
    'URL: http://www.allapi.net/
    'E-Mail: KPDTeam@Allapi.net
    Dim s As Long, l As Long, ln As Long, a$
    ReDim R(255) As RASENTRYNAME95
    Me.AutoRedraw = True
    R(0).dwSize = Len(R(0))
    s = 256 * R(0).dwSize
    l = RasEnumEntries(vbNullString, vbNullString, R(0), s, ln)
    For l = 0 To ln - 1
        a$ = StrConv(R(l).szEntryName(), vbUnicode)
        Me.Print Left$(a$, InStr(a$, Chr$(0)) - 1)
    Next
    If ln = 0 Then
        Me.Print "No Dial-Up connections found!"
    End If
End Sub


3)
Description:
The ExitWindowsEx function either logs off, shuts down, or shuts down and restarts the system.

Declaration:
Код: Выделить всё
Declare Function ExitWindowsEx Lib "user32" Alias "ExitWindowsEx" (ByVal uFlags As Long, ByVal dwReserved As Long) As Long


Parameters:
· uFlags
Specifies the type of shutdown. This parameter must be some combination of the following values:
EWX_FORCE
Forces processes to terminate. When this flag is set, Windows does not send the messages WM_QUERYENDSESSION and WM_ENDSESSION to the applications currently running in the system. This can cause the applications to lose data. Therefore, you should only use this flag in an emergency.
EWX_LOGOFF
Shuts down all processes running in the security context of the process that called the ExitWindowsEx function. Then it logs the user off.
EWX_POWEROFF
Shuts down the system and turns off the power. The system must support the power-off feature.
Windows NT: The calling process must have the SE_SHUTDOWN_NAME privilege. For more information, see the following Remarks section.
Windows 95: Security privileges are not supported or required.
EWX_REBOOT
Shuts down the system and then restarts the system.
Windows NT: The calling process must have the SE_SHUTDOWN_NAME privilege. For more information, see the following Remarks section.
Windows 95: Security privileges are not supported or required.
EWX_SHUTDOWN
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.
Windows NT: The calling process must have the SE_SHUTDOWN_NAME privilege. For more information, see the following Remarks section.
Windows 95: Security privileges are not supported or required.

· dwReserved
Reserved; this parameter is ignored.

Return Values:
If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Sample:
Код: Выделить всё
'In general section
Const EWX_LOGOFF = 0
Const EWX_SHUTDOWN = 1
Const EWX_REBOOT = 2
Const EWX_FORCE = 4
Private Declare Function ExitWindowsEx Lib "user32" (ByVal uFlags As Long, ByVal dwReserved As Long) As Long
Private Sub Form_Load()
    'KPD-Team 1998
    'URL: http://www.allapi.net/
    'E-Mail: KPDTeam@Allapi.net
    msg = MsgBox("This program is going to reboot your computer. Press OK to continue or Cancel to stop.", vbCritical + vbOKCancel + 256, App.Title)
    If msg = vbCancel Then End
    'reboot the computer
    ret& = ExitWindowsEx(EWX_FORCE Or EWX_REBOOT, 0)
End Sub


:idea:
Нет меня больше

Amed
Алфизик
Алфизик
 
Сообщения: 5346
Зарегистрирован: 09.03.2003 (Вс) 9:26

Сообщение Amed » 10.12.2003 (Ср) 22:28

А вот пример выхода из NT:

Код: Выделить всё
'In a module
Private Const EWX_LOGOFF = 0
Private Const EWX_SHUTDOWN = 1
Private Const EWX_REBOOT = 2
Private Const EWX_FORCE = 4
Private Const TOKEN_ADJUST_PRIVILEGES = &H20
Private Const TOKEN_QUERY = &H8
Private Const SE_PRIVILEGE_ENABLED = &H2
Private Const ANYSIZE_ARRAY = 1
Private Const VER_PLATFORM_WIN32_NT = 2
Type OSVERSIONINFO
    dwOSVersionInfoSize As Long
    dwMajorVersion As Long
    dwMinorVersion As Long
    dwBuildNumber As Long
    dwPlatformId As Long
    szCSDVersion As String * 128
End Type
Type LUID
    LowPart As Long
    HighPart As Long
End Type
Type LUID_AND_ATTRIBUTES
    pLuid As LUID
    Attributes As Long
End Type
Type TOKEN_PRIVILEGES
    PrivilegeCount As Long
    Privileges(ANYSIZE_ARRAY) As LUID_AND_ATTRIBUTES
End Type
Private Declare Function GetCurrentProcess Lib "kernel32" () As Long
Private Declare Function OpenProcessToken Lib "advapi32" (ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, TokenHandle As Long) As Long
Private Declare Function LookupPrivilegeValue Lib "advapi32" Alias "LookupPrivilegeValueA" (ByVal lpSystemName As String, ByVal lpName As String, lpLuid As LUID) As Long
Private Declare Function AdjustTokenPrivileges Lib "advapi32" (ByVal TokenHandle As Long, ByVal DisableAllPrivileges As Long, NewState As TOKEN_PRIVILEGES, ByVal BufferLength As Long, PreviousState As TOKEN_PRIVILEGES, ReturnLength As Long) As Long
Private Declare Function ExitWindowsEx Lib "user32" (ByVal uFlags As Long, ByVal dwReserved As Long) As Long
Private Declare Function GetVersionEx Lib "kernel32" Alias "GetVersionExA" (ByRef lpVersionInformation As OSVERSIONINFO) As Long
'Detect if the program is running under Windows NT
Public Function IsWinNT() As Boolean
    Dim myOS As OSVERSIONINFO
    myOS.dwOSVersionInfoSize = Len(myOS)
    GetVersionEx myOS
    IsWinNT = (myOS.dwPlatformId = VER_PLATFORM_WIN32_NT)
End Function
'set the shut down privilege for the current application
Private Sub EnableShutDown()
    Dim hProc As Long
    Dim hToken As Long
    Dim mLUID As LUID
    Dim mPriv As TOKEN_PRIVILEGES
    Dim mNewPriv As TOKEN_PRIVILEGES
    hProc = GetCurrentProcess()
    OpenProcessToken hProc, TOKEN_ADJUST_PRIVILEGES + TOKEN_QUERY, hToken
    LookupPrivilegeValue "", "SeShutdownPrivilege", mLUID
    mPriv.PrivilegeCount = 1
    mPriv.Privileges(0).Attributes = SE_PRIVILEGE_ENABLED
    mPriv.Privileges(0).pLuid = mLUID
    ' enable shutdown privilege for the current application
    AdjustTokenPrivileges hToken, False, mPriv, 4 + (12 * mPriv.PrivilegeCount), mNewPriv, 4 + (12 * mNewPriv.PrivilegeCount)
End Sub
' Shut Down NT
Public Sub ShutDownNT(Force As Boolean)
    Dim ret As Long
    Dim Flags As Long
    Flags = EWX_SHUTDOWN
    If Force Then Flags = Flags + EWX_FORCE
    If IsWinNT Then EnableShutDown
    ExitWindowsEx Flags, 0
End Sub
'Restart NT
Public Sub RebootNT(Force As Boolean)
    Dim ret As Long
    Dim Flags As Long
    Flags = EWX_REBOOT
    If Force Then Flags = Flags + EWX_FORCE
    If IsWinNT Then EnableShutDown
    ExitWindowsEx Flags, 0
End Sub
'Log off the current user
Public Sub LogOffNT(Force As Boolean)
    Dim ret As Long
    Dim Flags As Long
    Flags = EWX_LOGOFF
    If Force Then Flags = Flags + EWX_FORCE
    ExitWindowsEx Flags, 0
End Sub

'In a form
'This project needs a form with three command buttons
Private Sub Command1_Click()
    LogOffNT True
End Sub
Private Sub Command2_Click()
    RebootNT True
End Sub
Private Sub Command3_Click()
    ShutDownNT True
End Sub
Private Sub Form_Load()
    'KPD-Team 2000
    'URL: http://www.allapi.net/
    'E-Mail: KPDTeam@Allapi.net
    Command1.Caption = "Log Off NT"
    Command2.Caption = "Reboot NT"
    Command3.Caption = "Shutdown NT"
End Sub

neprden
Обычный пользователь
Обычный пользователь
 
Сообщения: 64
Зарегистрирован: 04.10.2003 (Сб) 19:37

Как програмно разорвать соединение

Сообщение neprden » 11.12.2003 (Чт) 17:46

Спасибо мужики завалили инфой все попробую
Кстате слышал что где то в недрах 98 есть файл типа krnl386
а нем ф-я выхода эффект которой сравним с reset (без посыла сообщений приложениям и службам) интересно есть такая в nt

RayShade
Scarmarked
Scarmarked
Аватара пользователя
 
Сообщения: 5511
Зарегистрирован: 02.12.2002 (Пн) 17:11
Откуда: Russia, Saint-Petersburg

Сообщение RayShade » 11.12.2003 (Чт) 17:50

В NT есть ExitWindowsEx очень даже неплохо работает.


Вернуться в Visual Basic 1–6

Кто сейчас на конференции

Сейчас этот форум просматривают: AhrefsBot и гости: 10

    TopList