初涉VB.NET入门级代码积累

来源:互联网 发布:笑郭网络验证 破解 编辑:程序博客网 时间:2024/05/09 18:57

[代码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 StringDim title As StringDim style As MsgBoxStyleDim response As MsgBoxResultmsg = "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 SystemImports System.IOImports 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 OnImports SystemImports System.IOClass 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 SubEnd 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