Mencari COM Port yang tersedia

Posted: November 26, 2008 in Programming, Visual Basic 6
Tag:, , , ,

Option Explicit

Public Declare Function CreateFile Lib “kernel32.dll” Alias _
“CreateFileA” (ByVal lpFileName As String, ByVal _
dwDesiredAccess As Long, ByVal dwShareMode As Long, _
lpSecurityAttributes As SECURITY_ATTRIBUTES, ByVal _
dwCreationDisposition As Long, ByVal _
dwFlagsAndAttributes As Long, ByVal hTemplateFile _
As Long) As Long

Public Declare Function CloseHandle Lib “kernel32.dll” _
(ByVal hObject As Long) As Long

‘API Structures
Public Type SECURITY_ATTRIBUTES
nLength As Long
lpSecurityDescriptor As Long
bInheritHandle As Long
End Type

‘API constants
Public Const FILE_SHARE_READ = &H1
Public Const FILE_SHARE_WRITE = &H2
Public Const OPEN_EXISTING = 3
Public Const FILE_ATTRIBUTE_NORMAL = &H80

Module

Public Function COMAvailable(COMNum As Integer) As Boolean
Dim hCOM As Long
Dim ret As Long
Dim sec As SECURITY_ATTRIBUTES

‘try to open the COM port
hCOM = CreateFile(“COM” & COMNum & “”, 0, FILE_SHARE_READ + _
FILE_SHARE_WRITE, sec, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0)
If hCOM = -1 Then
COMAvailable = False
Else
COMAvailable = True
‘close the COM port
ret = CloseHandle(hCOM)
End If
End Function

Usage

‘Usage:
Sub Command1_Click()
Dim i As Integer

For i = 1 To 16
If COMAvailable(i) Then
MsgBox “COM” & i & ” OK”, vbInformation
Else
MsgBox “COM” & i & ” Not OK”, vbExclamation
End If
Next
End Sub

Tinggalkan Balasan

Please log in using one of these methods to post your comment:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s