ユーザー名やコンピュータ名を取得するには

<システムインフォメーション表示ソフトを作ろう>

宣 言


Private Declare Function GetUserName& Lib "advapi32.dll" Alias "GetUserNameA" (ByVal NameBuff As String, Size As Long)
Private Declare Function GetComputerName& Lib "kernel32" Alias "GetComputerNameA" (ByVal NameBuff As String, Size As Long)

※Privateは必要に応じて削除またはPublicに変更

サ ン プ ル プ ロ グ ラ ム

まず、VisualBasicを起動してプロジェクトを新しく作成してください。まず、次のコードを貼り付け実行してください。メッセージを表示して終了します。

動作確認:Visual Basic 5.0(Visual Basic 4.0でも問題なく動作するはずです),Windows98

'APIの宣言
Private Declare Function GetUserName& Lib "advapi32.dll" Alias "GetUserNameA" (ByVal NameBuff As String, Size As Long)
Private Declare Function GetComputerName& Lib "kernel32" Alias "GetComputerNameA" (ByVal NameBuff As String, Size As Long)

Private Sub Form_Load()
Dim TmpUser As String * 255 '変数の宣言
Dim TmpComputer As String * 255
Dim User As String
Dim Computer As String
Dim i As Integer

GetUserName TmpUser, 255 'ユーザー名の取得
GetComputerName TmpComputer, 255 'コンピュータの名前を取得


For i = 1 To 255 '文字列をVB用に処理
If Asc(Mid$(TmpUser, i, 1)) = 0 Then
User = Mid$(TmpUser, 1, i - 1)
Exit For
End If
Next

For i = 1 To 255 '文字列をVB用に処理
If Asc(Mid$(TmpComputer, i, 1)) = 0 Then
Computer = Mid$(TmpComputer, 1, i - 1)
Exit For
End If
Next

'結果を表示
MsgBox "ユーザー名:" + User + Chr(13) + "コンピュータ名:" + Computer
End
End Sub

文字列をVB用に処理しないといけないのが面倒なんですよね。近いうちに本格的なサンプルも作成するつもりです。

トップに戻る
Visual Basicワンポイントテクニック目次に戻る

楽天モバイル[UNLIMITが今なら1円] ECナビでポインと Yahoo 楽天 LINEがデータ消費ゼロで月額500円〜!


無料ホームページ 無料のクレジットカード 海外格安航空券 解約手数料0円【あしたでんき】 海外旅行保険が無料! 海外ホテル