VB.NET覚書

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

2018-03-28

スクロールバーを一番下へスクロール

https://dobon.net/vb/dotnet/control/tbscrolltolast.html

'カレット位置を末尾に移動
TextBox1.SelectionStart = TextBox1.Text.Length
'テキストボックスにフォーカスを移動
TextBox1.Focus()
'カレット位置までスクロール
TextBox1.ScrollToCaret()
トラックバック - http://sub.g.hatena.ne.jp/garyo/20180328

2017-05-31

ExcelグラフVB.netで表示

http://www.officepro.jp/excelvba/chart/index4.html

'[参照設定の追加]-[COM]タブから

'Microsoft Excel xx.0 Object Libraryを選択する必要あり。

Imports Microsoft.Office.Core
Imports Microsoft.Office.Interop
Imports Microsoft.Office.Interop.Excel

Public Class ClsExcel

    Dim CurrentSheet As Integer

    Public Property ExcelObj As Excel.Application

    ''' <summary>
    ''' 現在のワークブック
    ''' </summary>
    ''' <remarks></remarks>
    Public Property Book As Excel.Workbook
    Private Property fileName As String
    ''' <summary>
    ''' 現在のワークシート
    ''' </summary>
    ''' <remarks></remarks>
    Public Property Sheet As Excel.Worksheet

    Public Sub New()
        ExcelObj = New Excel.Application()
        ExcelObj.Visible = True  ' Excel を表示する場合のみ
        ExcelObj.DisplayAlerts = False  ' 保存時の確認メッセージボックスを表示しない場合のみ
    End Sub



    ''' <summary>
    ''' ブックを開く
    ''' </summary>
    ''' <param name="fileName">Excelファイル</param>
    Public Sub Open(ByVal fileName As String)
        Book = ExcelObj.Workbooks.Open(fileName)
        CurrentSheet = 1
        Me.fileName = fileName
    End Sub
    ''' <summary>
    ''' 新しいブックを作成する
    ''' </summary>
    Public Sub CreateBook()
        Book = ExcelObj.Workbooks.Add()
        Sheet = Book.Worksheets(1)
    End Sub
    ''' <summary>
    ''' 新しいワークシートを追加する。
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub AddSheet()
        Sheet = Book.Worksheets.Add()
    End Sub
    ''' <summary>
    ''' ブックを選択する
    ''' </summary>
    Public Sub setBook(bookname As String)
        Sheet = Book.Worksheets(bookname)
    End Sub
    ''' <summary>
    ''' ブックを選択する
    ''' </summary>
    Public Sub setBookByNo(bookno As Integer)
        Sheet = Book.Worksheets(bookno)
    End Sub
    ''' <summary>
    ''' セルの値を得る
    ''' </summary>
    ''' <param name="row">行番号(1から始まる)</param>
    ''' <param name="col">列番号(1から始まる)</param>
    ''' <returns>セルの値</returns>
    Public Function GetCellValue(ByVal row As Integer, ByVal col As Integer) As Object
        Return Sheet.Cells(row, col).Value
    End Function

    ''' <summary>
    ''' セルに値を書く
    ''' </summary>
    ''' <param name="row">行番号(1から始まる)</param>
    ''' <param name="col">列番号(1から始まる)</param>
    ''' <param name="val">セルの値</param>
    Public Sub SetCellValue(ByVal row As Integer, ByVal col As Integer, ByVal val As Object)
        Sheet.Cells(row, col).Value = val
    End Sub

    ''' <summary>
    ''' レンジを読む
    ''' </summary>
    ''' <param name="rng">レンジ</param>
    ''' <returns>データテーブル</returns>
    Public Function GetRange(ByVal rng As String) As System.Data.DataTable
        Dim dr As DataRow
        Dim cells As String() = rng.Split(CChar(":"))
        ' Range オブジェクトを作成する。
        Dim r As Excel.Range
        If cells.Length = 1 Then
            r = Sheet.Range(cells(0))
        Else
            r = Sheet.Range(cells(0), cells(1))
        End If
        Dim dt As New System.Data.DataTable
        Dim cols As Integer = 1
        Dim rows As Integer = 1
        ' レンジのサイズを得る。
        If cells.Length > 1 Then
            cols = Asc(cells(1).Substring(0, 1)) - Asc(cells(0).Substring(0, 1)) + 1
            rows = Asc(cells(1).Substring(1, 1)) - Asc(cells(0).Substring(1, 1)) + 1
        End If
        ' カラムを追加する。
        For i = 1 To cols
            dt.Columns.Add()
        Next
        ' DataTable を作成する。
        For j = 1 To rows
            dr = dt.NewRow()
            For i = 1 To cols
                dr(i - 1) = r.Cells(j, i).Value
            Next
            dt.Rows.Add(dr)
        Next
        Return dt
    End Function
    ''' <summary>
    ''' ブックを閉じる
    ''' </summary>
    Public Sub Close()
        If Book IsNot Nothing Then
            Book.Close()
        End If
    End Sub

    ''' <summary>
    ''' Excel を閉じる
    ''' </summary>
    Public Sub Quit()
        ExcelObj.Quit()
    End Sub

    ''' <summary>
    ''' ブックをファイル保存する
    ''' </summary>
    ''' <param name="fileName">Excelワークブックのファイル名</param>
    Public Sub SaveAs(ByVal fileName As String)
        Book.SaveAs(fileName)
    End Sub

    ''' <summary>
    ''' ブックを上書き保存する
    ''' </summary>
    Public Sub Save()
        Book.Save()
    End Sub

    Public Sub test(f As Form1)
        Dim chartObj As ChartObject
        Dim chart1 As Chart

        chartObj = Sheet.ChartObjects(1)
        chart1 = chartObj.Chart
        chart1.SetSourceData(Book.Worksheets("Sheet1").Range("B2:E6"))

        chart1.Export(Filename:=My.Application.Info.DirectoryPath & "\test001.GIF", FilterName:="GIF")

        Using fs As System.IO.FileStream = New System.IO.FileStream(My.Application.Info.DirectoryPath & _
       "\test001.GIF", System.IO.FileMode.Open, System.IO.FileAccess.Read)
            f.PictureBox1.Image = System.Drawing.Image.FromStream(fs)
        End Using
    End Sub

End Class

Excel操作クラス

'[参照設定の追加]-[COM]タブから

'Microsoft Excel xx.0 Object Libraryを選択する必要あり。

Imports Microsoft.Office.Core
Imports Microsoft.Office.Interop

Public Class ClsExcel

    Dim CurrentSheet As Integer

    Public Property ExcelObj As Excel.Application

    ''' <summary>
    ''' 現在のワークブック
    ''' </summary>
    ''' <remarks></remarks>
    Public Property Book As Excel.Workbook
    Private Property fileName As String
    ''' <summary>
    ''' 現在のワークシート
    ''' </summary>
    ''' <remarks></remarks>
    Public Property Sheet As Excel.Worksheet

    Public Sub New()
        ExcelObj = New Excel.Application()
        ExcelObj.Visible = True  ' Excel を表示する場合のみ
        ExcelObj.DisplayAlerts = False  ' 保存時の確認メッセージボックスを表示しない場合のみ
    End Sub



    ''' <summary>
    ''' ブックを開く
    ''' </summary>
    ''' <param name="fileName">Excelファイル</param>
    Public Sub Open(ByVal fileName As String)
        Book = ExcelObj.Workbooks.Open(fileName)
        CurrentSheet = 1
        Me.fileName = fileName
    End Sub
    ''' <summary>
    ''' 新しいブックを作成する
    ''' </summary>
    Public Sub CreateBook()
        Book = ExcelObj.Workbooks.Add()
        Sheet = Book.Worksheets(1)
    End Sub
    ''' <summary>
    ''' 新しいワークシートを追加する。
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub AddSheet()
        Sheet = Book.Worksheets.Add()
    End Sub
    ''' <summary>
    ''' ブックを選択する
    ''' </summary>
    Public Sub setBook(bookname As String)
        Sheet = Book.Worksheets(bookname)
    End Sub
    ''' <summary>
    ''' ブックを選択する
    ''' </summary>
    Public Sub setBookByNo(bookno As Integer)
        Sheet = Book.Worksheets(bookno)
    End Sub
    ''' <summary>
    ''' セルの値を得る
    ''' </summary>
    ''' <param name="row">行番号(1から始まる)</param>
    ''' <param name="col">列番号(1から始まる)</param>
    ''' <returns>セルの値</returns>
    Public Function GetCellValue(ByVal row As Integer, ByVal col As Integer) As Object
        Return Sheet.Cells(row, col).Value
    End Function

    ''' <summary>
    ''' セルに値を書く
    ''' </summary>
    ''' <param name="row">行番号(1から始まる)</param>
    ''' <param name="col">列番号(1から始まる)</param>
    ''' <param name="val">セルの値</param>
    Public Sub SetCellValue(ByVal row As Integer, ByVal col As Integer, ByVal val As Object)
        Sheet.Cells(row, col).Value = val
    End Sub

    ''' <summary>
    ''' レンジを読む
    ''' </summary>
    ''' <param name="rng">レンジ</param>
    ''' <returns>データテーブル</returns>
    Public Function GetRange(ByVal rng As String) As DataTable
        Dim dr As DataRow
        Dim cells As String() = rng.Split(CChar(":"))
        ' Range オブジェクトを作成する。
        Dim r As Excel.Range
        If cells.Length = 1 Then
            r = Sheet.Range(cells(0))
        Else
            r = Sheet.Range(cells(0), cells(1))
        End If
        Dim dt As New DataTable
        Dim cols As Integer = 1
        Dim rows As Integer = 1
        ' レンジのサイズを得る。
        If cells.Length > 1 Then
            cols = Asc(cells(1).Substring(0, 1)) - Asc(cells(0).Substring(0, 1)) + 1
            rows = Asc(cells(1).Substring(1, 1)) - Asc(cells(0).Substring(1, 1)) + 1
        End If
        ' カラムを追加する。
        For i = 1 To cols
            dt.Columns.Add()
        Next
        ' DataTable を作成する。
        For j = 1 To rows
            dr = dt.NewRow()
            For i = 1 To cols
                dr(i - 1) = r.Cells(j, i).Value
            Next
            dt.Rows.Add(dr)
        Next
        Return dt
    End Function
    ''' <summary>
    ''' ブックを閉じる
    ''' </summary>
    Public Sub Close()
        If Book IsNot Nothing Then
            Book.Close()
        End If
    End Sub

    ''' <summary>
    ''' Excel を閉じる
    ''' </summary>
    Public Sub Quit()
        ExcelObj.Quit()
    End Sub

    ''' <summary>
    ''' ブックをファイル保存する
    ''' </summary>
    ''' <param name="fileName">Excelワークブックのファイル名</param>
    Public Sub SaveAs(ByVal fileName As String)
        Book.SaveAs(fileName)
    End Sub

    ''' <summary>
    ''' ブックを上書き保存する
    ''' </summary>
    Public Sub Save()
        Book.Save()
    End Sub

End Class

Public Class Form1

    Public Property m_CE As New ClsExcel

    Private Sub QuitQToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles QuitQToolStripMenuItem.Click
        End
    End Sub

    Private Sub BtnRead1_Click(sender As System.Object, e As System.EventArgs) Handles BtnRead1.Click

    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        m_CE.Open("C:\temp\book1.xlsx")
        m_CE.setBook("Sheet1")
        MsgBox(m_CE.GetCellValue(1, 1))
        m_CE.SetCellValue(2, 1, "ABC")
        MsgBox(m_CE.GetCellValue(2, 1))
        m_CE.Save()
        m_CE.Close()
        m_CE.Quit()
    End Sub

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


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

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