VB.NET覚書

VB.NETの覚書
[個人メモ] [仕事メモ] [アイデア] [Ruby]
[TIPS] [対応表] [コメント書き方] [.NET Tips] [VB中学校] [VB.NET の入門サイト] [VB.NET コーディング標準 ] [VBレスキュー] [NonSoft]

2017-05-24

パラメータファイルXML

<?xml version="1.0" encoding="utf-8"?>
<xRoot>
	<xDATA ID="SYSTEM_INFO">
		<PRDUCT_NAME>RS-415-0005</PRDUCT_NAME>
		<PARA_VERSION>1.00</PARA_VERSION>
		<STAGE_NO>101</STAGE_NO>
		<STAGE_NAME>101</STAGE_NAME>
	</xDATA>
	<xDATA ID="FILEPATH">
		<OK_DATA>C:\DATA\RS-415-0005\101\ok.dat</OK_DATA>
		<OK_BACKUP_DATA>C:\DATA_BACKUP\RS-415-0005\101\ok.dat</OK_BACKUP_DATA>
		<NG_DATA>C:\DATA\RS-415-0005\101\ng.dat</NG_DATA>
		<NG_BACKUP_DATA>C:\DATA_BACKUP\RS-415-0005\101\ng.dat</NG_BACKUP_DATA>
	</xDATA>
	<xDATA ID="OPTION">
		<DATA_SAVE>1</DATA_SAVE>
		<NG_DATA_SAVE>1</NG_DATA_SAVE>
		<NG_RETRY>1</NG_RETRY>
		<NG_STOP>1</NG_STOP>
	</xDATA>
	<xDATA ID="COM">
		<COM_PORT ID="1">
			<COM_NO>1</COM_NO>
			<COMMENT>製品通信用 RS-232C ポート番号</COMMENT>
		</COM_PORT>
		<COM_PORT ID="2">
			<COM_NO>2</COM_NO>
			<COMMENT>DMM 34401A用 RS-232C ポート番号</COMMENT>
		</COM_PORT>
	</xDATA>
	<xDATA ID="DB">
		<DB ID="1">
			<DB_PATH>C:\DATA\RS-415-0005\DB\IDDATA.mdb</DB_PATH>
			<COMMENT>管理DB</COMMENT>
		</DB>
	</xDATA>
	<xDATA ID="GPIB">
		<GPIB ID="1">
			<ADDRESS>1</ADDRESS>
			<COMMENT>System Supply</COMMENT>
		</GPIB>
		<GPIB ID="2">
			<ADDRESS>2</ADDRESS>
			<COMMENT>Digital Multi Meter 1</COMMENT>
		</GPIB>
		<GPIB ID="3">
			<ADDRESS>0</ADDRESS>
			<COMMENT>Not use</COMMENT>
		</GPIB>
		<GPIB ID="4">
			<ADDRESS>0</ADDRESS>
			<COMMENT>Not use</COMMENT>
		</GPIB>
		<GPIB ID="5">
			<ADDRESS>0</ADDRESS>
			<COMMENT>Not use</COMMENT>
		</GPIB>
		<GPIB ID="6">
			<ADDRESS>0</ADDRESS>
			<COMMENT>Not use</COMMENT>
		</GPIB>
		<GPIB ID="7">
			<ADDRESS>0</ADDRESS>
			<COMMENT>Not use</COMMENT>
		</GPIB>
		<GPIB ID="8">
			<ADDRESS>0</ADDRESS>
			<COMMENT>Not use</COMMENT>
		</GPIB>
		<GPIB ID="9">
			<ADDRESS>0</ADDRESS>
			<COMMENT>Not use</COMMENT>
		</GPIB>
		<GPIB ID="10">
			<ADDRESS>0</ADDRESS>
			<COMMENT>Not use</COMMENT>
		</GPIB>
		<GPIB ID="11">
			<ADDRESS>0</ADDRESS>
			<COMMENT>Not use</COMMENT>
		</GPIB>
		<GPIB ID="12">
			<ADDRESS>0</ADDRESS>
			<COMMENT>Not use</COMMENT>
		</GPIB>
		<GPIB ID="13">
			<ADDRESS>0</ADDRESS>
			<COMMENT>Not use</COMMENT>
		</GPIB>
	</xDATA>
	<xDATA ID="INSPECTION">
		<INSPECTION ID="1">
			<LOWER_LIMIT>1</LOWER_LIMIT>
			<HIGHER_LIMIT>1</HIGHER_LIMIT>
			<ITEM>初期設定</ITEM>
			<UNIT>-</UNIT>
		</INSPECTION>
		<INSPECTION ID="2">
			<LOWER_LIMIT>1</LOWER_LIMIT>
			<HIGHER_LIMIT>1</HIGHER_LIMIT>
			<ITEM>初期設定</ITEM>
			<UNIT>-</UNIT>
		</INSPECTION>
		<INSPECTION ID="3">
			<LOWER_LIMIT>0</LOWER_LIMIT>
			<HIGHER_LIMIT>1</HIGHER_LIMIT>
			<ITEM>K1</ITEM>
			<UNIT>Ω</UNIT>
		</INSPECTION>
	</xDATA>
</xRoot>


トラックバック - http://sub.g.hatena.ne.jp/garyo/20170524

2017-05-23

XML読み込み


Imports System.Xml

Public Class Form1

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

        Dim myXmlDocument As XmlDocument = New XmlDocument()

        myXmlDocument.Load("C:\PROJECT\VB2010\xml\test.xml")

        Dim node As XmlNode

        node = myXmlDocument.DocumentElement
        displaytree(node)


    End Sub

    Public Sub DisplayTree(node As XmlNode)
        If Not IsNothing(node) Then Format(node)

        If node.HasChildNodes Then
            node = node.FirstChild
            While Not IsNothing(node)
                DisplayTree(node)
                node = node.NextSibling
            End While
        End If
    End Sub

    Private Sub Format(node As XmlNode)

        If Not node.HasChildNodes Then
            Debug.Print(Strings.Chr(9) & node.Name & "<" & node.Value & ">")
        Else
            Debug.Print(node.Name)

            If XmlNodeType.Element = node.NodeType Then
                Dim map As XmlNamedNodeMap = node.Attributes
                Dim attrnode As Object

                For Each attrnode In map
                    Debug.Print(" " & CType(attrnode, XmlNode).Name & "<" & CType(attrnode, XmlNode).Value & ">")
                Next
            End If
            Debug.Print("")
        End If
    End Sub

End Class

XML書き出し

参考にしたサイト

http://blog.syo-ko.com/?eid=1227

Imports System.Xml
Imports System.Text

Public Class Form1

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

        Dim xEncode As Encoding = Encoding.GetEncoding(65001I) '65001がUTF8
        Dim xDocument As XmlDataDocument = New XmlDataDocument 'XMLドキュメント作成
        Dim xDeclaration As XmlDeclaration = xDocument.CreateXmlDeclaration("1.0", xEncode.BodyName, Nothing) 'ヘッダ部作成

        Dim xRoot As XmlElement = xDocument.CreateElement("ルート名")

        Call xDocument.AppendChild(xDeclaration)    'ヘッダー
        Call xDocument.AppendChild(xRoot)   'ルート

        Dim newNode As XmlElement = xDocument.CreateElement("子要素")
        Dim xValue As XmlText = xDocument.CreateTextNode("値")
        Dim newChild As XmlElement = xDocument.CreateElement("孫要素")

        Call newNode.AppendChild(newChild)

        'Call newNode.AppendChild(xValue)    '値を代入

        Call newNode.SetAttribute("属性名", "属性値")

        Call xRoot.AppendChild(newNode)  'ルートへ子要素を追加

        Call xDocument.Save("c:\temp\test.xml")

        xDeclaration = Nothing
        xRoot = Nothing
        xDocument = Nothing
        xEncode = Nothing


    End Sub
End Class
トラックバック - http://sub.g.hatena.ne.jp/garyo/20170523

2017-05-22

backgroundwarker バックグランド処理

Public Class Form1

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        If BackgroundWorker1.IsBusy = True Then
            MsgBox("動作中")
            Return
        End If

        BackgroundWorker1.WorkerSupportsCancellation = True
        BackgroundWorker1.WorkerReportsProgress = True
        BackgroundWorker1.RunWorkerAsync(Integer.Parse(TextBox1.Text))
    End Sub

    Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

        
        Dim start As Integer = CInt(e.Argument)

        If start < 1 Or start > 100 Then
            start = 1
        End If

        For i As Integer = start To 100
            If Me.BackgroundWorker1.CancellationPending = True Then
                e.Cancel = True
                Return
            End If

            System.Threading.Thread.Sleep(100)
            BackgroundWorker1.ReportProgress(i)
        Next
        e.Result = "終了"
    End Sub

    Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
        ProgressBar1.Value = e.ProgressPercentage
    End Sub

    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        BackgroundWorker1.CancelAsync()
    End Sub

    Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
        If e.Cancelled Then
            MsgBox("cancel")
        Else
            MsgBox(e.Result.ToString)
        End If
    End Sub

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

    End Sub
End Class


BackGrowndWorkerをクラス

以下のサイトを参考にしました。

https://msdn.microsoft.com/ja-jp/library/cc221403(v=vs.95).aspx

Imports System.ComponentModel

Public Class ClsBackGround

    ''' <summary>
    ''' backgroundWorker
    ''' </summary>
    Private m_backGroundWorker As BackgroundWorker

    ''' <summary>
    ''' 進捗状況
    ''' </summary>
    Public Property progress As Integer

    ''' <summary>
    ''' 出力
    ''' </summary>
    Public Property result As String

    ''' <summary>
    ''' 終了状態
    ''' </summary>
    Public Property resultStatus As String

    ''' <summary>
    ''' 作業終了
    ''' </summary>
    Public Event Complete As EventHandler

    ''' <summary>
    ''' 進捗
    ''' </summary>
    Public Event ProgressChange As EventHandler

    ''' <summary>
    ''' 作業内容
    ''' </summary>
    Public Event DoWork As EventHandler
    Public Const ST_DONE = "Done!"
    Public Const ST_ERROR = "Error:"
    Public Const ST_CANCEL = "Canceled!"


    Sub New()
        m_backGroundWorker = New BackgroundWorker

        AddHandler m_backGroundWorker.DoWork, AddressOf m_backGroundWorker_DoWork
        AddHandler m_backGroundWorker.ProgressChanged, AddressOf m_backGroundWorker_ProgressChanged
        AddHandler m_backGroundWorker.RunWorkerCompleted, AddressOf m_backGroundWorker_RunWorkerCompleted

    End Sub

    Public Function start(Optional ByRef value As String = "") As Boolean

        If Not m_backGroundWorker.IsBusy Then
            resultStatus = ""
            m_backGroundWorker.WorkerSupportsCancellation = True
            m_backGroundWorker.WorkerReportsProgress = True
            m_backGroundWorker.RunWorkerAsync(value)
            Return True
        Else
            Return False
        End If

    End Function

    Public Sub cancel()

        m_backGroundWorker.CancelAsync()

    End Sub

    Public Function isBusy() As Boolean

        Return m_backGroundWorker.IsBusy

    End Function

    Private Sub m_backGroundWorker_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs)

        RaiseEvent DoWork(sender, e)

    End Sub

    Private Sub m_backGroundWorker_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs)

        progress = e.ProgressPercentage
        RaiseEvent ProgressChange(sender, e)

    End Sub

    Private Sub m_backGroundWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)

        result = ""

        If e.Cancelled = True Then
            resultStatus = ST_CANCEL
        ElseIf e.Error IsNot Nothing Then
            resultStatus = ST_ERROR & e.Error.Message
        Else
            resultStatus = ST_DONE
            result = e.Result
        End If

        RaiseEvent Complete(sender, e)

    End Sub

    Public Sub setProgress(value As Integer, ByRef sender As Object)

        Dim worker As System.ComponentModel.BackgroundWorker = CType(sender, System.ComponentModel.BackgroundWorker)

        If 0 <= value And 100 >= value Then
            worker.ReportProgress(value)
        End If

    End Sub


    Public Function isCancel(ByRef sender As Object, ByRef e As System.ComponentModel.DoWorkEventArgs) As Boolean

        Dim Ret As Boolean = False

        Dim worker As System.ComponentModel.BackgroundWorker = CType(sender, System.ComponentModel.BackgroundWorker)

        If worker.CancellationPending = True Then
            e.Cancel = True
            Ret = True
        Else
            Ret = False
        End If

        Return Ret

    End Function

    Public Function getArgment(e As System.ComponentModel.DoWorkEventArgs) As String
        Return e.Argument
    End Function

    Public Sub setResult(res As String, e As System.ComponentModel.DoWorkEventArgs)
        e.Result = res
    End Sub


End Class



Public Class Form1

    Dim WithEvents bw As ClsBackGround


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

        bw.start("5")

    End Sub


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

        bw = New ClsBackGround

    End Sub

    Private Sub bw_Complete(sender As Object, e As System.EventArgs) Handles bw.Complete

        MsgBox(bw.resultStatus & " " & bw.result)

    End Sub

    Private Sub bw_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bw.DoWork

        Dim start As Integer = Integer.Parse(bw.getArgment(e))

        For i = start To 10
            If bw.isCancel(sender, e) = True Then
                Exit For
            Else
                System.Threading.Thread.Sleep(500)
                bw.setProgress(i * 10, sender)
            End If
        Next

        bw.setResult("END", e)

    End Sub

    Private Sub bw_ProgressChange(sender As Object, e As System.EventArgs) Handles bw.ProgressChange

        Me.ProgressBar1.Value = bw.progress

    End Sub

    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click

        bw.cancel()

    End Sub
End Class

Process サンプル

参考にしたサイト

http://www.atmarkit.co.jp/fdotnet/chushin/introwinform_05/introwinform_05_02.html

Public Class Form1

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Me.Process1.StartInfo.FileName = "notepad.exe"
        Me.Process1.Start()
    End Sub

    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        Me.Process1.WaitForExit()
        MessageBox.Show( _
          Me.Process1.StartInfo.FileName & " 終了", _
          Me.Text, _
          MessageBoxButtons.OK)
    End Sub

    Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
        Me.Process1.Kill()
    End Sub
End Class

EventLogサンプル

参考にしたサイト

http://www.atmarkit.co.jp/fdotnet/chushin/introwinform_05/introwinform_05_02.html

Public Class Form1
    Private Sub Button1_Click( _
    ByVal sender As Object, ByVal e As EventArgs) _
        Handles Button1.Click
        If Me.TextBox1.Text.Length > 0 Then
            Me.EventLog1.Source = "Application"
            Me.EventLog1.WriteEntry(Me.TextBox1.Text)
        End If
    End Sub

    Private Sub Button2_Click( _
        ByVal sender As Object, ByVal e As EventArgs) _
            Handles Button2.Click
        If Me.TextBox1.Text.Length > 0 Then
            EventLog.WriteEntry("Application", _
                                Me.TextBox1.Text, _
                                EventLogEntryType.Warning)
        End If
    End Sub
End Class
トラックバック - http://sub.g.hatena.ne.jp/garyo/20170522

2017-05-19

Event

http://rucio.a.la9.jp/main/dotnet/shokyu/standard49.htm

class


Public Class Class1

    Public Event Pop As EventHandler

    Public Sub DoAnything()

        RaiseEvent Pop(Me, New EventArgs)

    End Sub

End Class
Public Class Form1

    Dim WithEvents Tester1 As New Class1

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

        Tester1.DoAnything()

    End Sub

    Private Sub Tester1_Pop(sender As Object, e As System.EventArgs) Handles Tester1.Pop
        MsgBox("Pop!")
    End Sub

End Class
トラックバック - http://sub.g.hatena.ne.jp/garyo/20170519

2017-05-08

パスからファイル名、拡張子などの情報を取得する

http://dobon.net/vb/dotnet/file/pathclass.html

まずは、パス文字列からいろいろな情報を取得する例を紹介します。指定するパス文字列ファイル(あるいはフォルダ)は、存在している必要はありません。

VB.NET

コードを隠すコード選択

'ディレクトリ名の取得

Console.WriteLine( _

System.IO.Path.GetDirectoryName( _

"C:\My Documents\My Pictures\サンプル.jpg"))

'結果: C:\My Documents\My Pictures

'拡張子の取得

Console.WriteLine( _

System.IO.Path.GetExtension( _

"C:\My Documents\My Pictures\サンプル.jpg"))

'結果: .jpg

'ファイル名の取得

Console.WriteLine( _

System.IO.Path.GetFileName( _

"C:\My Documents\My Pictures\サンプル.jpg"))

'結果: サンプル.jpg

'ファイル名(拡張子なし)の取得

Console.WriteLine _

(System.IO.Path.GetFileNameWithoutExtension( _

"C:\My Documents\My Pictures\サンプル.jpg"))

'結果: サンプル

'ルートディレクトリ名の取得

Console.WriteLine( _

System.IO.Path.GetPathRoot( _

"C:\My Documents\My Pictures\サンプル.jpg"))

'結果: C:\

トラックバック - http://sub.g.hatena.ne.jp/garyo/20170508