初涉VB.NET入門級代碼積累

[代碼1]
說明:這就是取消關閉的事件,執行對窗體退出方面的控制。
其中沒見過的只有Dispose()這個方法,MSDN裏看到是釋放某託管對象的應用,還不瞭解。日後懂了再記錄於此。


   

    Protected Overloads Overrides Sub OnClosing(ByVal e As System.ComponentModel.CancelEventArgs)
        e.Cancel = True
        Me.WindowState = FormWindowState.Minimized
        Hide()
        '----------------------------------------------------------------------------
        '顯示()
        'Me.Show()
        'Me.WindowState = FormWindowState.Normal
        '隱藏()
        'Me.WindowState = FormWindowState.Minimized
        '退出()
        'Me.Dispose()
        'Me.Hide()
        '----------------------------------------------------------------------------
    End Sub
  

 
   
[代碼2]
說明:這簡單的幾個字,就實現了按關聯打開文件。這在從前要調API才能實現。事情簡單了不少。
功能:啓用關聯的進程打開所選中的文件。


            Dim pr As New Process '新建一個進程類
            pr.Start("C:/test.txt") '打開的文件
            pr.Close() '關閉進程

[代碼3]

說明:MessageBox的調用,改變了的某些地方
功能:不必說了吧。
應用:隨處可見。

·參數資料

成員   值 說明 
--------------------------------------------------------------------------------------------------------
OKOnly   0 只顯示“確定”按鈕。
OKCancel  1 顯示“確定”和“取消”按鈕。
AbortRetryIgnore 2 顯示“中止”、“重試”和“忽略”按鈕。
YesNoCancel   3 顯示“是”、“否”和“取消”按鈕。
YesNo     4 顯示“是”和“否”按鈕。
RetryCancel   5 顯示“重試”和“取消”按鈕。
........................................................................................................
Critical   16 顯示“關鍵消息”圖標。
Question  32 顯示“警告查詢”圖標。
Exclamation   48 顯示“警告消息”圖標。
Information  64 顯示“信息消息”圖標。
........................................................................................................
DefaultButton1  0 第一個按鈕是默認的。
DefaultButton2  256 第二個按鈕是默認的。
DefaultButton3  512 第三個按鈕是默認的。
........................................................................................................
ApplicationModal 0 應用程序是有模式的。用戶必須響應消息框,才能繼續在當前應用程序中工作。
SystemModal  4096 系統是有模式的。所有應用程序都被掛起,直到用戶響應消息框。
........................................................................................................
MsgBoxSetForeground 65536 指定消息框窗口爲前景窗口。
MsgBoxRight  524288 文本爲右對齊。
MsgBoxRtlReading 1048576 指定文本應爲在希伯來語和阿拉伯語系統中從右到左顯示。
--------------------------------------------------------------------------------------------------------
第一組值 (0–5) 描述對話框中顯示的按鈕數量和類型。
第二組值 (16, 32, 48, 64) 描述圖標樣式。
第三組值 (0, 256, 512) 確定默認使用哪個按鈕。
第四組值 (0, 4096) 確定消息框的模式性,
第五組值指定消息框窗口是否爲前臺窗口,以及文本對齊和方向。
將這些數字相加以生成 Buttons 參數的最終值時,只能由每組值取用一個數字。


·返回值

常數   值 
OK  1
Cancel  2
Abort  3
Retry  4
Ignore  5
Yes   6
No   7
 

·例程:

Dim msg As String
Dim title As String
Dim style As MsgBoxStyle
Dim response As MsgBoxResult
msg = "Do you want to continue?"   '定義信息內容
style = MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Critical Or MsgBoxStyle.YesNo  '用OR連接常量,常量的表達方式屬性化
title = "MsgBox Demonstration"   ' 標題,沒可說的
'調對話框的顯示,接收返回值
response = MsgBox(msg, style, title)
'依用戶選擇做處理
If response = MsgBoxResult.Yes Then   
   ' Perform some action.
Else
   ' Perform some other action.
End If
 



[代碼4]
說明:這是經過C# to VB.NET引擎轉換的結果,我做了修整,正確運行沒問題了。爲了保證日後的應用,我保留了C#的代碼以應不時之需。
功能:以二進制讀/寫文件的例子,這是爲日後處理一些數據文件做準備。很多時候數據沒辦法以文本形式保存。如果想應用加密算法,也需要以二進制方式按結構存儲。

Imports System
Imports System.IO
Imports System.Text

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        '寫二進制文件
        Dim bw As BinaryWriter
        Dim fs As FileStream = New FileStream("C:/mydata.data", FileMode.Create)
        bw = New BinaryWriter(fs)
        Dim i As Integer = 0
        While i < 200
            bw.Write(i)
            System.Math.Min(System.Threading.Interlocked.Increment(i), i - 1)
        End While
        bw.Close()
    End Sub
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        '讀二進制文件
        Dim br As BinaryReader
        Dim str As String = ""
        Dim fs As FileStream = New FileStream("C:/mydata.data", FileMode.Open)
        br = New BinaryReader(fs)
        Dim i As Integer = 0
        While i < fs.Length / 4
            str += br.ReadInt32.ToString
            System.Math.Min(System.Threading.Interlocked.Increment(i), i - 1)
        End While
        TextBox1.Text = str
    End Sub





[代碼5]
說明:一個來自MSDN的關於讀寫數據文件的例程。中間涉及了BinaryWriter 和 BinaryReader兩個操作二進制讀寫的類。

Option Explicit On 
Option Strict On
Imports System
Imports System.IO
Class MyStream
    Private Const FILE_NAME As String = "Test.data"
    Public Shared Sub Main()
        ' Create the new, empty data file.
        If File.Exists(FILE_NAME) Then
            Console.WriteLine("{0} already exists!", FILE_NAME)
            Return
        End If
        Dim fs As New FileStream(FILE_NAME, FileMode.CreateNew)
        ' Create the writer for data.
        Dim w As New BinaryWriter(fs)
        ' Write data to Test.data.
        Dim i As Integer
        For i = 0 To 10
            w.Write(CInt(i))
        Next i
        w.Close()
        fs.Close()
        ' Create the reader for data.
        fs = New FileStream(FILE_NAME, FileMode.Open, FileAccess.Read)
        Dim r As New BinaryReader(fs)
        ' Read data from Test.data.
        For i = 0 To 10
            Console.WriteLine(r.ReadInt32())
        Next i
        r.Close()
        fs.Close()
    End Sub
End Class

·原C#代碼

private void Button3_Click(object sender, System.EventArgs e)
  {
   //寫二進制文件
   BinaryWriter bw;
      //創建一個二進制文件
   FileStream fs=new FileStream (MapPath("mydata.data"),FileMode.Create );
   bw=new BinaryWriter (fs);//初始化一個BinaryWriter
   for(int i=0;i<200;i++)
    bw.Write (i);//寫入
   bw.Close ();//關閉
  }
private void Button4_Click(object sender, System.EventArgs e)
  {
   //讀二進制文件
   BinaryReader br;
   string str="";
   FileStream fs=new FileStream (MapPath("mydata.data"),FileMode.Open );
   br=new BinaryReader (fs);  
   for(int i=0;i<fs.Length /4;i++)
     str+=br.ReadInt32 ().ToString ();
   TextBox1.Text =str;
  }


[代碼6]
說明:這是更新爲用緩衝區讀取拷貝文件的代碼,4096原來是NTFS下一個簇的大小,雖然代碼中留出了自定義單位的可選參數,但不在必要時不要去改變。拷貝過程抽象爲一個FORM的私有方法,其間輸出顯示的代碼還可以再簡化。

    Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
        Dim str As String
        Select Case BinCopyFile(TextBox1.Text, TextBox2.Text)
            Case 0
                str = "複製成功完成!"
            Case 1
                str = "源文件不存在。"
            Case 2
                str = "源文件與目標文件不能爲同一文件。"
            Case 3
                str = "因輸出文件已存在而且不允許覆蓋,操作被取消。"
            Case Else
        End Select
        MsgBox(str, MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "操作結果")
    End Sub

    Private Function BinCopyFile(ByVal SourceFile As String, ByVal CopyToFile As String, Optional ByVal MAX As Integer = 4096)
        '判斷"SourceFile"-源文件是否存在.
        If Not File.Exists(SourceFile) Then
            Console.WriteLine("錯誤:源文件不存在。[BY BinCopyfile()]")
            Return 1
        End If
        '判斷源文件與目標文件是否爲同一文件
        If SourceFile = CopyToFile Then
            Console.WriteLine("錯誤:源文件與目標文件不能爲同一文件。[BY BinCopyfile()]")
            Return 2
        End If
        '判斷"CopyToFile"-被拷貝文件是否已存在,存在時詢問是否覆蓋.
        If File.Exists(CopyToFile) Then
            If MsgBox("目標文件已經存在,是否覆蓋?", MsgBoxStyle.YesNo Or MsgBoxStyle.Question, "覆蓋文件提示") = MsgBoxResult.No Then
                Console.WriteLine("用戶指示:因輸出文件已存在而且不允許覆蓋,操作被取消。[BY BinCopyfile()]")
                Return 3
            End If
        End If
 

        '建立讀取,寫入文件的兩個對象      
        Dim br As BinaryReader
        Dim bw As BinaryWriter
        Dim fsr As FileStream = New FileStream(SourceFile, FileMode.Open, FileAccess.Read)
        Dim fsw As FileStream = New FileStream(CopyToFile, FileMode.Create)
        br = New BinaryReader(fsr)
        bw = New BinaryWriter(fsw)
        '建立緩衝
        If MAX > fsr.Length Then MAX = fsr.Length
        Dim Buffer(MAX) As Byte

        '建立異常處理
        Try
            Dim I As Double
            Dim N As Double = fsr.Length
            Do
                Buffer = br.ReadBytes(MAX)
                bw.Write(Buffer)
                I = fsr.Position
                Label1.Text = CStr(Int(I / 1024)) & "K /" & CStr(Int(N / 1024)) & "K [" & CStr(Int(I / N * 100)) & "%]"
                Application.DoEvents()
            Loop While I < N
        Catch ex As IOException
            MsgBox(ex.Message.ToString, MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly, "I/O錯誤!")
        Finally
            bw.Close()
            br.Close()
        End Try

        '返回值
        Return 0
    End Function

       
       
[代碼7]
說明:我也沒想到,現在改一個屬性還要以一個堆對象來更新它。font現在是一個對象了,它的屬性是隻讀的了。只能再建一個新的跟它一樣對象先賦好值,再用這個對象的句柄替換掉原屬性的句柄引用,讓引用指到新賦值的對象上去。不知原對象是被怎麼處理掉的。

 

       Dim CurrentSize As Single
        CurrentSize = Label1.Font.Size
        CurrentSize += 2.0F
        'CurrentSize -= 2.0F
        Label1.Font = New Font(Label1.Font.Name, CurrentSize, Label1.Font.Style, Label1.Font.Unit)

Font類 構造函數 重載列表

名稱 說明 
Font (IntPtr) 由 .NET Compact Framework 支持。
Font (Font, FontStyle) 初始化新 Font,它使用指定的現有 Font 和 FontStyle 枚舉。
Font (FontFamily, Single) 使用指定的大小初始化新 Font。
Font (String, Single) 使用指定的大小初始化新 Font。 
Font (FontFamily, Single, FontStyle) 使用指定的大小和樣式初始化新 Font。 由 .NET Compact Framework 支持。 
Font (FontFamily, Single, GraphicsUnit) 使用指定的大小和單位初始化新的 Font。將此樣式設置爲 FontStyle.Regular。 
Font (String, Single, FontStyle) 使用指定的大小和樣式初始化新 Font。 由 .NET Compact Framework 支持。 
Font (String, Single, GraphicsUnit) 使用指定的大小和單位初始化新的 Font。將樣式設置爲 FontStyle.Regular。 
Font (FontFamily, Single, FontStyle, GraphicsUnit) 使用指定的大小、樣式和單位初始化新的 Font。 
Font (String, Single, FontStyle, GraphicsUnit) 使用指定的大小、樣式和單位初始化新的 Font。 
Font (FontFamily, Single, FontStyle, GraphicsUnit, Byte) 使用指定的大小、樣式、單位和字符集初始化新的 Font。
Font (String, Single, FontStyle, GraphicsUnit, Byte) 使用指定的大小、樣式、單位和字符集初始化新的 Font。 
Font (FontFamily, Single, FontStyle, GraphicsUnit, Byte, Boolean) 使用指定的大小、樣式、單位和字符集初始化新的 Font。
Font (String, Single, FontStyle, GraphicsUnit, Byte, Boolean) 使用指定的大小、樣式、單位和字符集初始化新 Font。 


-------------------------------------------------------------
Font.Unit 屬性 
是一個GraphicsUnit,它表示此 Font 的度量單位。這是一個枚舉,成員如下:

Display 指定顯示設備的度量單位。通常,視頻顯示使用的單位是像素;打印機使用的單位是 1/100 英寸。 
Document 將文檔單位(1/300 英寸)指定爲度量單位。 
Inch 將英寸指定爲度量單位。 
Millimeter 將毫米指定爲度量單位。 
Pixel 將設備像素指定爲度量單位。 
Point 將打印機點(1/72 英寸)指定爲度量單位。 
World 將世界座標系單位指定爲度量單位。 

-------------------------------------------------------------
FontStyle 屬性
也是一個枚舉,也就是說它包括了表示字體樣式中的粗體,斜體,下劃線等成員屬性。另外我還看到了很多“方法”。

成員名稱 - 說明 
Bold - 加粗文本。 
Italic - 傾斜文本。 
Regular - 普通文本。 
Strikeout - 中間有直線通過的文本。 
Underline - 帶下劃線的文本。


[代碼8]
說明:首先,需要一個Webbrowser1。這代碼的功能是在當前目錄建立一個HTML結構的頁面,然後以file協議導航到上面。代碼目前有四種可選,允許擴充。

    Dim FilePath As String = My.Application.Info.DirectoryPath & "/deskWeb.htm"  '相當於VB6的 App.path & "/filename.ext",不過不必再擔心根目錄時“//”的問題了。
    Private Sub BuildWeb(ByVal N As Integer)
        Dim WriteString As String
        Select Case N
            Case 1
                '代碼1 2008倒記時
                WriteString = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=gb2312'><title>北京2008奧運倒計時</title></head><body topmargin='0' leftmargin='0'><script src='http://www.clocklink.com/embed.js'></script><script type='text/javascript' language='JavaScript'>obj = new Object;obj.clockfile = '2008olympic001-orange.swf';obj.TimeZone = 'CCT';obj.width = 450;obj.height = 150;obj.DayU = 'days';obj.HourU = 'hrs';obj.MinU = 'min';obj.SecU = 'sec';obj.Target = '2008,8,8,8,8,0';obj.wmode = 'transparent';showClock(obj);</script></body></html>"
                Me.Width = 460 : Me.Height = 170
            Case 2
                '代碼2 時鐘
                WriteString = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=gb2312'><title>clock</title></head><body topmargin='0' leftmargin='0'><P align=center><embed src='http://www.clocklink.com/clocks/0003-Green.swf?TimeZone=CCT' width='200' height='200' wmode='transparent' type='application/x-shockwave-flash'></P></body></html>"
                Me.Width = 210 : Me.Height = 210
            Case 3
                '代碼3 數字時鐘
                WriteString = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=gb2312'><title>clock</title></head><body topmargin='0' leftmargin='0'><P align=center><embed src='http://www.clocklink.com/clocks/5005-green.swf?TimeZone=CCT&'  width='180' height='60' wmode='transparent' type='application/x-shockwave-flash'></P></body></html>"
                Me.Width = 190 : Me.Height = 85
             Case Else
                WriteString = "<font size=3 color='#FF0000'>發生調用錯誤,未找到指定代碼。</font>"
        End Select
        '寫入到文件中
        My.Computer.FileSystem.WriteAllText(FilePath, WriteString, False)
        '導航到頁面,並做異常檢測
        Try
            WebBrowser1.Navigate(New Uri("file:///" & FilePath))
        Catch ex As System.UriFormatException
            Return
        End Try
    End Sub


 

[代碼9]
說明:一些雜七雜八的東西.

 

   '這兩個事件中的代碼,就能讓窗體激活時顯示,不激活時變透明.注意Opactity取值是[0,1]區間.
    Private Sub Form2_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
        Me.Opacity = 1
    End Sub
    Private Sub Form2_Deactivate(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Deactivate
        Me.Opacity = 0.5
    End Sub

 

   '控件的size屬性使其做到了縮放匹配,代碼銳減,如果多個控件要保持格局縮放則有控件實現.用代碼算座標的時代結束啦.
    Private Sub Form2_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
        TextBox1.Size = Me.Size
    End Sub

 

   '文本文件讀寫
    Dim FastText As String = My.Application.Info.DirectoryPath & "/FastText.tmp"
    ' My.Application.Info.DirectoryPath 當前程序所在路徑
    ' My.Computer.FileSystem.GetTempFileName 生成一個空的臨時文件在TEMP路徑下(不必加文件名了)
    
    My.Computer.FileSystem.WriteAllText(FastText, TextBox1.Text, False)
    '寫入文件.第二個參數不允許爲空.第三的參數的布爾值是指示是否覆蓋已存在文件的.還有第四個參數,默認UTF-8
    TextBox1.Text = My.Computer.FileSystem.ReadAllText(FastText)
    '讀取就只要路徑,將返回值賦值就可以了,同樣有第二個參數,默認UTF-8

  '窗體與屏幕
    Me.SetDesktopLocation( X,Y)        '窗體移動到X,Y
    My.Computer.Screen.Bounds.Width    'Screen.Width
    My.Computer.Screen.Bounds.Height   'Screen.Height 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章