ソース掲示板




すべてから検索

キーワード   条件 表示 現行ログ 過去ログ トピックス 名前 本文
VB.NET 部品サンプル
日時: 2008/05/03 14:31
名前: lightbox



★ ログ出力クラス
★ ini ファイルアクセス
★ 連想配列に順次階層をためる
★ オブジェクトに対するオペレータの定義
★ Form のカスタマイズサンプル 
メンテナンス

ログ出力クラス ( No.1 )
日時: 2008/04/24 23:56
名前: lightbox


日時: 2008/04/24 23:56
名前: lightbox
拡張子:
● プログラムのパス
● メソッドの引数の省略時の定義
● HOST 名、IP アドレス
● ログインユーザー名
● デバッグ(構成)時のみ実行される処理
● 現在の時刻
拡張子:
Imports System.IO
Imports System.Windows.Forms

Public Class DEBUG

	Public path As String
	Public handle As StreamWriter
	Public handleRead As StreamReader

	' ********************************************************
	' (コンストラクタの定義)( Sub で定義する )
	' ********************************************************
	Public Sub New(ByVal Messaege As String)

#If DEBUG Then
		path = Application.StartupPath()
		path &= "\debug.log"

		handle = New StreamWriter(path, True)
		Me.Write(Application.ExecutablePath & " を開始しました")
		Me.Write("インスタンス作成時:" & Messaege)

		Dim pc As String = System.Net.Dns.GetHostName()
		Dim ip As String = System.Net.Dns.GetHostEntry(pc).AddressList(0).ToString()
		Dim login As String = Environment.UserName
		Me.Write("****** " & login & vbTab & pc & vbTab & ip & " ******")
#End If

	End Sub

	' ********************************************************
	' 書き込み
	' ********************************************************
	Public Sub Write(Optional ByVal Messaege As String = "")

#If DEBUG Then
		Dim str As String = DateTime.Now.ToString()
		str &= vbTab & Messaege

		handle.WriteLine(str)
#End If

	End Sub

	' ********************************************************
	' 終了
	' ********************************************************
	Public Sub Quit()

#If DEBUG Then
		Me.Write(Application.ExecutablePath & " を終了します")
		Me.Write()
		handle.Flush()
		handle.Close()
#End If

	End Sub


End Class
拡張子:
Module Module1

	Sub Main()

		Dim log As DEBUG = New DEBUG("ログ出力を開始します")

		log.Write("主処理")

		log.Write("終了処理")

		log.Quit()

	End Sub

End Module
このアーティクルの参照用URLをクリップボードにコピー メンテナンス
ini ファイルアクセス ( No.2 )
日時: 2008/10/19 14:08
名前: lightbox
関数として
拡張子:
Imports System.Text
Imports System.Runtime.InteropServices

Module Module2

	' ******************************************************
	' ini ファイル書き込み
	' ******************************************************
	<DllImport("Kernel32.dll", CharSet:=CharSet.Auto)> _
	Public Function WritePrivateProfileString( _
	   ByVal lpAppName As String, _
	   ByVal lpKeyName As String, _
	   ByVal lpString As String, _
	   ByVal lpFileName As String) As Integer
	End Function

	' ******************************************************
	' ini ファイル読み込み
	' ******************************************************
	<DllImport("Kernel32.dll", CharSet:=CharSet.Auto)> _
	Public Function GetPrivateProfileString( _
	   ByVal lpAppName As String, _
	   ByVal lpKeyName As String, _
	   ByVal lpDefault As String, _
	   ByVal lpReturnedString As StringBuilder, _
	   ByVal nSize As Integer, _
	   ByVal lpFileName As String) As Integer
	End Function

End Module
拡張子:
Imports System.Text
Imports System.Windows.Forms

Module Module1

	Sub Main()

		Dim ini As String = Application.StartupPath() & "\connect.ini"

		Module2.WritePrivateProfileString("Database", "Oracle", "localhost/ORCL", ini)

		Dim str As StringBuilder = New StringBuilder(512)

		GetPrivateProfileString("Database", "Oracle", "", str, 512, ini)

		Console.WriteLine(str.ToString())

		Console.ReadLine()

	End Sub

End Module

クラスとして
拡張子:
Imports System.Text
Imports System.Runtime.InteropServices

Public Class INI

	Public ini As String

	' ******************************************************
	' ini ファイル読み込み
	' ******************************************************
	<DllImport("Kernel32.dll", CharSet:=CharSet.Auto)> _
	Private Shared Function GetPrivateProfileString( _
	   ByVal lpAppName As String, _
	   ByVal lpKeyName As String, _
	   ByVal lpDefault As String, _
	   ByVal lpReturnedString As StringBuilder, _
	   ByVal nSize As Integer, _
	   ByVal lpFileName As String) As Integer
	End Function

	' ******************************************************
	' ini ファイル書き込み
	' ******************************************************
	<DllImport("Kernel32.dll", CharSet:=CharSet.Auto)> _
	Private Shared Function WritePrivateProfileString( _
	   ByVal lpAppName As String, _
	   ByVal lpKeyName As String, _
	   ByVal lpString As String, _
	   ByVal lpFileName As String) As Integer
	End Function

	' ********************************************************
	' (コンストラクタの定義)( Sub で定義する )
	' ********************************************************
	Public Sub New(ByVal path As String)

		ini = path

	End Sub

	' ******************************************************
	' 取得
	' ******************************************************
	Public Function GetValue(ByVal Section As String, ByVal Entry As String) As String

		Dim str As StringBuilder = New StringBuilder(512)

		GetPrivateProfileString(Section, Entry, "", str, 512, ini)

		GetValue = str.ToString()

	End Function

	' ******************************************************
	' 書き込み
	' ******************************************************
	Public Sub SetValue(ByVal Section As String, ByVal Entry As String, ByVal Value As String)

		WritePrivateProfileString(Section, Entry, Value, ini)

	End Sub

End Class
拡張子:
Imports System.Windows.Forms

Module Module1

	Sub Main()

		Dim ini As INI = New INI(Application.StartupPath() & "\connect.ini")

		ini.SetValue("Database", "Oracle", "localhost/ORCL")

		Console.WriteLine(ini.GetValue("Database", "Oracle"))

		Console.ReadLine()

	End Sub

End Module
このアーティクルの参照用URLをクリップボードにコピー メンテナンス
連想配列に順次階層をためる ( No.3 )
日時: 2008/04/29 01:26
名前: lightbox
この処理では、AllDirectories オプションで一度に取得できますが、
他の階層構造データで、不可能な場合の方法の一つ。
リモートの FTP ディレクトリの全ての階層のファイルを取得するのに使えます

拡張子:
Imports System.IO

Module Module1

	Sub Main()

		Dim target As String = "C:\Documents and Settings\lightbox\My Documents"

		Dim dir As New Dictionary(Of Integer, String)
		Dim dir_name As String = ""
		Dim dir_cnt As Integer = 1
		Dim idx_cnt As Integer = 1
		dir.Add(dir_cnt, target)

		Dim subFolders As String()
		Do While (True)

			subFolders = Directory.GetDirectories( _
			  dir(idx_cnt), _
			  "*", _
			  SearchOption.TopDirectoryOnly _
			)
			For Each dir_name In subFolders
				dir_cnt += 1
				dir.Add(dir_cnt, dir_name)
				Console.WriteLine(dir_name)
			Next

			idx_cnt += 1
			If Not dir.TryGetValue(idx_cnt, dir_name) Then
				Exit Do
			End If

		Loop

		Console.ReadLine()

	End Sub

End Module
このアーティクルの参照用URLをクリップボードにコピー メンテナンス
オブジェクトに対するオペレータの定義 ( No.4 )
日時: 2008/05/05 23:03
名前: lightbox

C++ での実装とは少し違うようですが、以下のような演算子を自分の作成したオブジェクト
に対して特別な実装を施す事ができます


OperatorOperand CountDescription
+UnaryPositive
-UnaryNegative
IsFalseUnaryIs False test
IsTrueUnaryIs True test
NotUnaryNegation
+BinaryAddition
-BinarySubtraction
*BinaryMultiplication
/BinaryFloating-point division
\BinaryInteger division
&BinaryConcatenation
^BinaryExponentiation
>>BinaryShift right
<<BinaryShift left
=BinaryEquality; assignment
cannot be overloaded
<>BinaryNot equal
>BinaryGreater than
<BinaryLess than
>=BinaryGreater than or equal to
<=BinaryLess than or equal to
AndBinaryBitwise and
LikeBinaryString pattern matching
ModBinaryModulo division
OrBinaryBitwise or
XorBinaryBitwise xor
CTypeUnaryType conversion
拡張子:
実装時に知っておく必要のある仕様としては、

1) クラスメソッドとして定義する必要がえる
2) ペアとなる演算子は同時に定義する必要がある
3) 演算子によっては、引数の型が決められているものがある
4) 第1引数に、自分自身の型を定義する事によって呼ばれた時にインスタンスが引き渡される
テスト用のレジストリを扱うクラス
拡張子:
' **************************************************
' クラス定義
' **************************************************
Imports Microsoft.Win32

Public Class RegCur

	Public regkey As RegistryKey = Nothing
	Public svpath As String = Nothing


	' **************************************************
	' コンストラタ
	' **************************************************
	Public Sub New(ByVal path As String)

		regkey = Registry.CurrentUser.OpenSubKey(path, True)
		svpath = path

	End Sub

	' **************************************************
	' 比較演算子を代入して再OPENに利用
	' **************************************************
	Public Shared Operator =(ByVal target As RegCur, ByVal path As String) As Boolean

		Dim ret As Boolean = False

		If Not target.regkey Is Nothing Then
			target.regkey.Close()
		End If

		target.regkey = Registry.CurrentUser.OpenSubKey(path, True)
		If Not target.regkey Is Nothing Then
			ret = True
		End If

		Return ret

	End Operator

	' **************************************************
	' 比較演算子を代入して再OPENに利用
	' **************************************************
	Public Shared Operator <>(ByVal target As RegCur, ByVal path As String) As Boolean

		Dim ret As Boolean = False

		If Not target.regkey Is Nothing Then
			target.regkey.Close()
		End If

		target.regkey = Registry.CurrentUser.OpenSubKey(path, True)
		If target.regkey Is Nothing Then
			ret = True
		End If

		Return ret

	End Operator

	' **************************************************
	' C++ で言うところの キャスト演算子( String 用 )
	' Widening は 損失の無い変換
	' **************************************************
	Public Shared Widening Operator CType(ByVal value As RegCur) As String

		If value Is Nothing Then
			Return ""
		Else
			Return value.svpath
		End If

	End Operator

	' **************************************************
	' 演算子では無いが、String 用の Ctype と同じにする
	' デフォルトでは、クラス名が返る(含む名前空間)
	' **************************************************
	Public Overrides Function ToString() As String

		Return Me.svpath

	End Function

End Class
拡張子:
レジストリのキーを再度別のキーで開けなおす際に、 = の右辺がキーで、成功した時に true が返ります。
<> を使うと、成功した時に false が返ります。

( ※ = と <> は、本来比較演算子です )
実行サンプル
拡張子:
Imports Microsoft.Win32

Public Class Form1

	Private Sub Form1_Load(ByVal sender As System.Object, _
	 ByVal e As System.EventArgs) Handles MyBase.Load

		Dim reg As RegCur = New RegCur("Environment")

		MessageBox.Show(reg.regkey.GetValue("PATH").ToString())

		If reg = "Software\Microsoft\Ftp" Then
			MessageBox.Show(CStr(reg.regkey.GetValue("Use PASV")))
		Else
			MessageBox.Show("キーが存在しません")
		End If

		If reg = "Software\Microsoft\Internet Explorer" Then
			MessageBox.Show(CType(reg.regkey.GetValue("Download Directory"), String))
		Else
			MessageBox.Show("キーが存在しません")
		End If

		If reg <> "Environment" Then
			MessageBox.Show("キーが存在しません")
		Else
			MessageBox.Show(Convert.ToString(reg.regkey.GetValue("TMP")))
		End If

	End Sub
End Class
拡張子:
VB.NET では、通常自作オブジェクトを = や <> 演算子で比較しないので問題無いですが、
このまま C# に変換した場合は、C# では null との比較が存在するので考慮が必要です

VB での オブジォクトがインスタンスかどうかの判断
if Object is Nothing then
	' もともと is Nothing を使うので、= オペレターは使われない
end if

C# での オブジォクトがインスタンスかどうかの判断
if ( null == Object ) {
	// null を左辺に持って来る事によって、定義された == オペレータは発動しない
end if
C#
拡張子:
public class RegCur
{

	public RegistryKey regkey = null;
	public string svpath = null;

	public RegCur(string path)
	{

		regkey = Registry.CurrentUser.OpenSubKey(path, true);
		svpath = path;

	}

	public static bool operator ==(RegCur target, string path)
	{
		bool ret = false;

		if ((target.regkey != null))
		{
			target.regkey.Close();
		}

		target.regkey = Registry.CurrentUser.OpenSubKey(path, true);
		if ((target.regkey != null))
		{
			ret = true;
		}

		return ret;

	}

	public static bool operator !=(RegCur target, string path)
	{

		bool ret = false;

		if ((target.regkey != null))
		{
			target.regkey.Close();
		}

		target.regkey = Registry.CurrentUser.OpenSubKey(path, true);
		if (target.regkey == null)
		{
			ret = true;
		}

		return ret;

	}

}
このアーティクルの参照用URLをクリップボードにコピー メンテナンス
Form のカスタマイズサンプル ( No.5 )
日時: 2008/05/03 14:26
名前: lightbox

● 閉じるボタンをクリックしても、反応しないようにする
● そのかわりに、ESC キーで確認ダイアログを出して終了させる
● 共通の初期化処理
● Enter キーで 次のコントロールに移動するようにする


拡張子:
Partial Class Form1

	' ******************************************************
	' 閉じるボタンを無効にする
	' ******************************************************
	Protected Overrides Sub WndProc( _
	 ByRef message As System.Windows.Forms.Message)

		' WinUser.h
		' #define WM_SYSCOMMAND		0x0112
		' #define SC_CLOSE			0xF060

		If message.Msg = &H112 And message.WParam.ToInt32() = &HF060 Then
			Return
		End If

		MyBase.WndProc(message)

	End Sub

	' ******************************************************
	' KeyPress での処理を有効にする為の割り込み
	' ******************************************************
	Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)

		MyBase.KeyPreview = True
		MyBase.OnLoad(e)

	End Sub

	' ******************************************************
	' Enter キーで次のコントロールへ移動
	' ( フォームの KeyPreview : True )
	' SelectNextControl パラメータの説明
	' 【forward】
	' タブ オーダー内を前方に移動する場合は true。後方に移動する場合は false。 
	' 【tabStopOnly】
	' TabStop プロパティが false に設定されているコントロールを無視する場合は true。
	' 【nested】
	' 入れ子になった (子コントロールの子) 子コントロールを含める場合は true。 
	' 【wrap】
	' タブ オーダーの最後のコントロールに到達した後、
	' タブ オーダーの最初のコントロールから検索を続行する場合は true 
	'
	' ★ ボタンの場合は押された事になります
	' ******************************************************
	Protected Overrides Sub OnKeyPress(ByVal e As System.Windows.Forms.KeyPressEventArgs)

		If e.KeyChar = ControlChars.Cr Then
			Me.SelectNextControl(Me.ActiveControl, True, True, True, True)
			e.Handled = True
		End If

		MyBase.OnKeyPress(e)

	End Sub

	' ******************************************************
	' ESC による終了処理
	' ******************************************************
	Protected Overrides Sub OnKeyDown(ByVal e As System.Windows.Forms.KeyEventArgs)

		If e.KeyCode = Keys.Escape Then
			If MessageBox.Show( _
			 "終了しますか?", _
			 "ESC", _
			 MessageBoxButtons.YesNo, MessageBoxIcon.Question _
			 ) = Windows.Forms.DialogResult.Yes Then
				Application.Exit()
			End If

		End If

		MyBase.OnKeyDown(e)
	End Sub


End Class
● 初期処理として、起動していない場合は MySQL をサービスで実行させる ● 一つのボタンに対して二つの処理を行う
拡張子:
' ↓参照設定が必要
Imports System.ServiceProcess

Public Class Form1

	Private Sub Form1_Load(ByVal sender As System.Object, _
	 ByVal e As System.EventArgs) Handles MyBase.Load

		' サービスが実行されていない場合にサービスを実行
		Dim sc As New ServiceController()
		sc.ServiceName = "MySQL51"
		If sc.Status = ServiceProcess.ServiceControllerStatus.Stopped Then
			sc.Start()
		End If

	End Sub

	Private Sub Button1_Click(ByVal sender As System.Object, _
	ByVal e As System.EventArgs) Handles Button1.Click

		MessageBox.Show("Push")

	End Sub

	Private Sub Button2_Click(ByVal sender As System.Object, _
	 ByVal e As System.EventArgs) Handles Button1.Click

		Application.Exit()

	End Sub

End Class
このアーティクルの参照用URLをクリップボードにコピー メンテナンス