1 / 61

درس برنامه سازی پیشرفته 2 Visual Basic.NET

درس برنامه سازی پیشرفته 2 Visual Basic.NET. 3 نمره کلاسی (به ازای هر غیبت 0/5 نمره کسر) 5 نمره تمرینات کلاسی ( تحویل به موقع ) 12 نمره عملی پایان ترم. سرفصل ها :. برخی از تفاوتهای VB و VB.Net تبدیل برنامه های VB6 به VB.Net کار با توابع API

fritz
Télécharger la présentation

درس برنامه سازی پیشرفته 2 Visual Basic.NET

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. درس برنامه سازی پیشرفته 2Visual Basic.NET

  2. 3 نمره کلاسی (به ازای هر غیبت 0/5 نمره کسر) 5 نمره تمرینات کلاسی ( تحویل به موقع ) 12 نمره عملی پایان ترم

  3. سرفصل ها : • برخی از تفاوتهای VB و VB.Net • تبدیل برنامه های VB6 به VB.Net • کار با توابع API • آرایه ها، LBound و UBound و For Each و مقدار دهی اولیه و آرایه های پویا و آرایه کنترلی (زمان طراحی و اجرا) و آرایه ای ازاشیاء مختلف(اشاره به Typeof) • کلاس Array ، Array.Resize • آرگومان اختیاری (Optional)، نامدار، با طول متغییر(ParamArray) بعنوان آخرین آرگومان، مقداری (ByVal) و ارجاع (ByRef) • امکانXML documentation (’’’) برای توابع و نوع ها (Structure) • متغییر Static

  4. File System Object با استفاده از Microsoft Scripting Runtime (COM Reference) و Imports Scripting • ImageList و Menus & Toolbars و ListView و TreeView • System.IO و FileIO.FileSystem و FileSystem • Dialogs و Rich TextBox و Tab Control و ToolTip • Structure و Enum و Collection • Files • گرافیک و Printing و اشیاء مربوطه • کلاس My(Computer.Screen, Application.Info, CommandLineArgs, GetEnvironmentVariable, ..), Math • Err(.number, .Description) و Debug و Exceptions • Clipboard • پایگاه داده : Data و اشیاء مربوطه – ویزارد و کدنویسی - Sql, Access • Reporting و اشیاء مربوطه شامل Crystal Report

  5. Registry • کلاس ها و Class Diagram • تولید DLL و امکان <ToolboxBitmap(imageFile)> • استفاده و الگو برداری از فرمهای آماده مثل About Box, Dialog, Explorer Form, Login Form, MDIParent Form, Splash Screen • Web Application • Mobile Programming • Threading • Setup سازی

  6. برخی از تفاوتهای VB و VB.Net 1- خصوصیت پیش فرض نداریم (Default Property). بعنوان مثال در VB ، Text1.text =“ali” ≡ Text1=“ali” 2- هنگام فراخوانی توابع و زیربرنامه ها، باید بعد از نام آنها () بگذاریم. در VB دراین مورد تناقضاتی هم وجود دارد. 3- وجود AndAlso علاوه بر And و OrElse علاوه بر Or برای بررسی شرط به اندازه لزوم یا بررسی کامل شرط. 4- تعریف متغییر اجباری است. همینطور : Dim x, y As Integer : Dim z As Integer = 10 5- عملگر += که از C به ارث رسیده است (و -= و *= و . . . ): S += n ≡ s = s + n

  7. 6- در VB.Net بر خلاف VB در توابع و سابروتین، اگر نحوه فراخوانی یا پاس کردن پارامترها (Call By Reference & Call By Value) تعیین نشود، بصورت پیش فرض ByVal در نظر گرفته میشود. 7- تعریف متغییرها میتواند به یک بلوک با پایان End یا Loop یا Next هم محدود شود(Block level Scope). (درون انواع حلقه ها و شروط و ... ) 8- End While بجای Wend. 9- آرگومان های Optional ، نیاز به مقدار پیش فرض دارند. (Optional Arguments Require a Default Value) 10- توابع و سابروتین ها، نمیتوانند Static تعریف شوند. تعریف آنها بصورت Static ، باعث میشود متغییرهای آنها Static شوند.

  8. 11- مقدار بازگشتی توابع توسط دستورReturn برگردانده شود. البته میتواند توسط نام آنها هم برگردانده شود. 12- بجای متد SetFocus از Select استفاده میشود. 13- ابعاد آرایه از صفر شروع میشوند. امکان تعریف، با شروع از عدد دیگری امکان پذیر نیست. As Byte Dim a(3) As Byte ≡ Dim a(0 to 3) 14- امکان انتساب آرایه ها (حتی با ابعاد متفاوت): Dim a(3) As Byte, b(3) As Byte a(0) = 1 : a(3) = 6 b = a 'b = a.Clone()

  9. 15- دستور Option Strict On باعث میشود، تبدیل نوع داده هایی که باعث تخریب داده میشوند ، امکان پذیر نباشد. مثلا انتساب متغییری از نوع Long به Integer . Option Strict On disallows implicit conversions from Long to Integer. 16- متغییرها Object هستند. زیر کلاس از کلاس Object. Dim x As String x = "Hello, World" MsgBox(x.Length) 17- نوع داده Short معادلInt16 وInteger معادل Int32 و Long معادل Int64 است.

  10. 18- تبدیل داده های دیگر به String : Dim x As Integer = 1234567, y As String y = x ‘ y = CStr(x) ‘ y = x.ToString البته Str(x) کاملا معادل سه دستور فوق نیست . (فضای خالی قبل از عدد مثبت) y = x.ToString(“0,0”) ‘ 1,234,567 (سه رقم سه رقم) 19- رشته با طول ثابت ( Fixed-Length Strings ) پشتیبانی نمیشود. البته در مبحث رکوردها، متعاقبا توضیح داده خواهد شد. 20- نوع داده Variant با نوع داده Object با اندازه 4 بایت جایگزین شده است که آدرس حافظه ای که داده مورد نظر در آن ذخیره خواهد شد، را نگه میدارد. Dim x ≡ Dim x as Object 21- Structure بجای UDT(User Data Type) یا رکورد قرار گرفته است.

  11. تبدیل برنامه های VB6 به VB.Net پروژه ایجاد شده توسط VB را با استفاده از گزینه Open Project… از منوی File و گذراندن مراحل درخواستی، تبدیل کنید. معادل بعضی از دستورات VB را میتوانید از گزینه Upgrade Visual Basic 6 Code … از منوی Tools البته در حالت کد نویسی، بخواهید.

  12. کار با توابع API اغلب کاستی های VB6 که باعث نیاز به توابع API ویندوز می شد، در VB.net افزوده شده است مثل توابع کار با رجیستری ( کلاس Microsoft.Win32.Registry) وتوابع تشخیص بزرگی و کوچکی و نوع کاراکترها (کلاس Char)و ... در موارد دیگر، نحوه کار با توابع API مانند VB6 است . با این تفاوت که در تعاریف، نوع داده Long به Integer و Integer به Short تبدیل گردد. بدیهی است که بجای Type هم، باید از Structure استفاده شود.

  13. آرایه ها Dim n(10) As Integer 'Dim n(0 To 10) As Integer Dim m(1 To 10) As Integer ‘Error:Array lower bounds can be only '0‘ MsgBox(LBound(n)) '0 MsgBox(UBound(n)) '10 MsgBox(n.Length) '11 For i As Integer = n.GetLowerBound(0) To n.GetUpperBound(0) n(i) = I Next For Each x As Integer In n MsgBox(x) Next Dim p(2, 3) As Byte Dim x() As Integer = {1, 2, 3, 4} Dim y(,) As Byte = {{1, 2, 3}, {5, 6, 7}} 'm(0 to 1, 0 to 2) ReDim Preserve x(2) '{1, 2, 3}

  14. آرایه کنترلی زمان طراحی شیوه کار با VB6 متفاوت است. پس از گذاشتن اشیاء یا کنترلهای مورد نظر روی فرم، الف) آنها را انتخاب می کنیم. ب ) از نوار ابزار پنجره Properties ،گزینه Events را انتخاب می کنیم. ج ) روی رویداد مورد نظر دابل کلیک می کنیم یا نام مناسبی را تایپ کرده و آنگاه دابل کلیک می کنیم. د ) کد مربوطه را وارد می کنیم . (sender عضو مورد نظر در آرایه است) البته میتوان رویداد مربوط به یکی از کنترلها را با افزودن همان رویداد اشیاء دیگر یا حتی هر رویداد هم نوع آن در انتهای عنوان آن روال بسط داد. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, TextBox1.MouseHover MsgBox(sender.text) End Sub

  15. آرایه کنترلی زمان اجرا Private Sub Form1_Load(ByVal sender As Object, ByVal e As ... Dim btn(3) As Button For i As Byte = 0 To 3 btn(i) = New Button With btn(i) .Parent = Me .Top = i * .Height + 10 .Text = i AddHandler .Click, AddressOfbtn_click End With Next End Sub Private Sub btn_click(ByVal s As Object, ByVal e As EventArgs) MsgBox(s.text) End Sub

  16. آرایه ای از اشیاء مختلف Dim b1 As New Button With {.Text = "b1", .Top = 10} Dim b2 As New Button With {.Text = "b2", .Top = 40} Dim t As New TextBox With {.Top = 70, .Text=“Test”} Dim a(2) As Object a.SetValue(b1, 0) a.SetValue(b2, 1) a.SetValue(t, 2) For Each obj As Object In a obj.Parent = Me If TypeOfobj Is Button Then MsgBox(obj.text) End If Next

  17. با فرض اینکه تعدادی شیئ ( دکمه، کادر متن و ...) روی فرم داشته باشیم ، فشردن دکمه یک ، آنها را در آرایه قرار می دهد و دکمه دو ، کادرهای متن را نهان و دکمه سه، آن ها را آشکار می نماید. Dim obj() As Object Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As . . . ReDim obj(Me.Controls.Count) For index As Integer = 0 To Me.Controls.Count - 1 obj(index) = Me.Controls(index) Next End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As . . . For index As Integer = 0 To Me.Controls.Count - 1 'If Not (obj(index) Is Button3) Then ‘ همه اشیاء غیر از دکمه سه If TypeOf obj(index) Is TextBox Then obj(index).visible = False End If Next End Sub Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As . . . For index As Integer = 0 To Me.Controls.Count - 1 obj(index).visible = True Next End Sub www.ali-arabi.com

  18. کلاس Array در VB6 دستور Array برای مقدار دهی اولیه آرایه است . در اینجا کلاس Array کلاس پایه همه آرایه ها است. برخی از امکانات آن : Dim n() As Integer = {10, 2, 3} Array.Resize(n, 5) ' {10, 2, 3, 0, 0} Array.Resize(n, 2) ' {10, 2} Array.Sort(n) '{2, 10} Array.Reverse(n) ' {10, 2} MsgBox(Array.IndexOf(n, 2)) ' 1 Dim m() As Integer = {1, 3, 5, 7} Array.Copy(n, m, 1) ' m:{10, 3, 5, 7} در صورت وجود فضای کافی Dim a() As Byte = {1, 2, 3, 4, 5} Dim b() As Byte = {10, 20, 30, 40} Array.Copy(a, 1, b, 2, 2) ' b:{10, 20, 2, 3} Dim c(6) As Byte a.CopyTo(c, 1) ' c:{0, 1, 2, 3, 4, 5, 0}

  19. آرگومان های توابع و زیر برنامه ها: الف ) آرگومان اختیاری (Optional) : Function MyFunc(ByVal x As Byte, Optional ByVal y As Byte = 20, Optional ByVal z As Byte = 30) As Integer Return x + y + z End Function Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles . . . MsgBox(MyFunc(1)) ‘51 MsgBox(MyFunc(1, 2)) ‘33 MsgBox(MyFunc(1, 2, 3)) ‘6 End Sub آرگومان های بعد از یک آرگومان اختیاری ، باید اختیاری باشند مقدار دهی اجباری

  20. ب ) آرگومان نامدار : Function MyFunc(ByVal x As Byte, ByVal y As Byte) As Single Return x / y End Function Private Sub Button1_Click(ByVal sender As System.Object, . . . MsgBox(MyFunc(20, 10)) ‘2 MsgBox(MyFunc(y:=10, x:=20)) ‘2 End Sub

  21. ج ) آرگومان با طول متغییر : Function MyFunc(ByValParamArray n() As Byte) As Integer Dim s As Integer = 0 For index As Integer = 0 To n.Length - 1 s += n(index) Next Return s End Function Private Sub Button1_Click(ByVal sender As . . . MsgBox(MyFunc(20, 10)) ‘30 MsgBox(MyFunc(1, 2, 3, 4)) ‘10 End Sub فقط آخرین آرگومان

  22. د ) آرگومان های مقداری و ارجاعی (Call By Value, Call By Reference): Sub MySub(ByVal x As Byte, ByRef y As Byte) x += 1 y += 1 MsgBox(x + y) ‘ 22 End Sub Private Sub Button1_Click(ByVal sender As . . . Dim a As Byte = 10, b As Byte = 10 MySub(a, b) MsgBox(a) ‘ 10 MsgBox(b) ‘ 11 End Sub

  23. XML Documentation : Public Class Form1 ''' <summary> ''' This Function Give 2 Number and Return Divide of them ''' </summary> ''' <param name="x"> مقسوم </param> ''' <param name="y">مقسوم علیه</param> ''' <returns> حاصل تقسیم در قالب عدد اعشاری </returns> ''' <remarks>تابع محاسبه تقسیم </remarks> Function MyFunc(ByVal x As Integer, ByVal y As Integer) As Single Dim s As Single = x / y Return s End Function Private Sub Button1_Click(ByVal sender As System.Object, ByVal e . . . Dim x As Single = MyFunc(10, 20) End Sub End Class www.ali-arabi.com

  24. متغییر ایستا (static) : Function updateSales(ByVal thisSale As Decimal) As Decimal Static totalSales As Decimal = 0 totalSales += thisSale Return totalSales End Function Private Sub Button1_Click(ByVal sender As . . . MsgBox(updateSales(1000)) '1000 MsgBox(updateSales(2500)) '3500 End Sub

  25. کار با فونت ها: TextBox1.Font.Size = 20 خطا ( فقط خواندنی ) TextBox1.Font = New Font(TextBox1.Font.Name, 20, TextBox1.Font.Style) افزودن تمام فونتهای نصب شده روی سیستم به لسیت For Each f As FontFamily In FontFamily.Families ListBox1.Items.Add(f.Name) Next یا Dim fnt As New System.Drawing.Text.InstalledFontCollection For Each f As FontFamily In fnt.Families ListBox2.Items.Add(f.Name) Next www.ali-arabi.com

  26. File System Object : Imports Scripting Public Class Form1 Dim fso As New FileSystemObject Dim t As TextStream Private Sub Button1_Click(ByVal sender As System.Object, . . . Dim p As String = fso.BuildPath("c:\windows", "a.txt")‘c:\windows\a.txt t = fso.CreateTextFile("c:\a\f.txt") t.Write(RichTextBox1.Text) t.Close() For Each d As Drive In fso.Drives RichTextBox1.Text += d.DriveLetter & " " & d.DriveType.ToString() & vbNewLine Next p = fso.GetAbsolutePathName("c:\\windows/a.txt") 'c:\windows\a.txt p = fso.GetBaseName("c:\a\abc.txt") 'abc Dim drv As Drive = fso.GetDrive("c:\") Dim f As File = fso.GetFile("c:\a\f.txt") MsgBox(f.Size & vbNewLine & f.Type) Dim fldr As Folder = fso.GetFolder("c:\") For Each subfldr As Folder In fldr.SubFolders RichTextBox1.Text += subfldr.Name & vbNewLine Next MsgBox(fso.GetSpecialFolder(SpecialFolderConst.WindowsFolder).Path) End Sub Private Sub Button2_Click(ByVal sender As System.Object, . . . t = fso.OpenTextFile("c:\a\f.txt") RichTextBox1.Text = t.ReadAll() t.Close() End Sub End Class ابتدا Project  Add Reference <COM Tab> Microsoft Scripting Runtime

  27. ListView, TreeView : Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ListView1.Columns.Add("Name") ListView1.Columns.Add("Ext") Dim lvi As ListViewItem = ListView1.Items.Add("F3", 2) lvi.SubItems.Add("10") For v As View = View.LargeIcon To View.Tile ComboBox1.Items.Add(v) Next Dim tn As TreeNode = TreeView1.Nodes.Add("t1", "t1") Dim tn11 As TreeNode = tn.Nodes.Add("t11") tn11.Nodes.Add("t111") tn11.Nodes.Add("t112") tn.Nodes.Add("t12") TreeView1.Nodes.Add("t2", "t2") TreeView1.Nodes.Add("t3", "t3") TreeView1.ExpandAll() TreeView1.CheckBoxes = True End Sub Private Sub ListView1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListView1.Click If ListView1.SelectedItems.Count > 0 Then MsgBox(ListView1.SelectedItems(0).Text) End If End Sub Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect ListView1.Clear() For Each tn As TreeNode In TreeView1.SelectedNode.Nodes ListView1.Items.Add(tn.Text) Next End Sub www.ali-arabi.com

  28. System.IO : Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click IO.Directory.CreateDirectory("c:\b\c") ‘ حتی اگر فولدر مورد نظر نباشد Dim d As System.IO.Directory d.CreateDirectory("c:\c") Dim d As New IO.DirectoryInfo("c:\windows") MsgBox(d.CreationTime) Dim x As Integer For Each di As IO.DirectoryInfo In d.GetDirectories() x = di.Attributes And IO.FileAttributes.Hidden If x = IO.FileAttributes.Hidden Then ListBox1.Items.Add(di.FullName) End If Next For Each f As IO.FileInfo In d.GetFiles() ListBox1.Items.Add(f.FullName) Next IO.File.Create("c:\a\abc.txt") Dim file As New IO.FileStream("c:\a\abc.txt", IO.FileMode.OpenOrCreate, IO.FileAccess.Write) For i As Byte = 1 To 10 file.WriteByte(i) Next file.Close() End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Dim file As New IO.FileStream("c:\a\abc.txt", IO.FileMode.OpenOrCreate, IO.FileAccess.Read) Dim i As Byte While file.Position < file.Length i = file.ReadByte() ListBox1.Items.Add(i) End While file.Close() End Sub www.ali-arabi.com

  29. FileIO.FileSystem و FileSystem : For Each fn As String In FileIO.FileSystem.FindInFiles("c:\windows", "Class", True, FileIO.SearchOption.SearchTopLevelOnly, "*.txt", "*.log") ListBox1.Items.Add(fn) Next FileSystem.ChDir("c:\windows\system32") MsgBox(FileSystem.CurDir("c:")) Dim fn As String = FileSystem.Dir("c:\*.*", FileAttribute.Archive + FileAttribute.Hidden) While fn <> "" ListBox1.Items.Add(fn) fn = FileSystem.Dir() End While www.ali-arabi.com

  30. Dialogs و RichTextBox و Tab Control و ToolTip : If ColorDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then TextBox1.BackColor = ColorDialog1.Color End If FolderBrowserDialog1.ShowNewFolderButton = False FolderBrowserDialog1.Description = "Select A Folder ... " If FolderBrowserDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then TextBox1.Text = FolderBrowserDialog1.SelectedPath() End If Dim fntdlg As New FontDialog With {.ShowColor = True, .Font = RichTextBox1.SelectionFont} fntdlg.Color = RichTextBox1.SelectionColor If fntdlg.ShowDialog() = Windows.Forms.DialogResult.OK Then RichTextBox1.SelectionFont = fntdlg.Font RichTextBox1.SelectionColor = fntdlg.Color End If OpenFileDialog1.Filter = "Text Files|*.txt|All Files|*.*" OpenFileDialog1.Multiselect = True If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then For Each fn As String In OpenFileDialog1.FileNames RichTextBox1.Text += fn & vbNewLine Next End If RichTextBox1.SaveFile("c:\a\b.dat", RichTextBoxStreamType.RichText) RichTextBox1.HideSelection = False RichTextBox1.LoadFile("c:\a\b.dat", RichTextBoxStreamType.RichText) Dim tp As New TabPage("Test") tp.BackColor = Color.Beige Dim txt As New TextBox With {.Text = "Ok", .Parent = tp} TabControl1.TabPages.Add(tp) Dim tt As New ToolTip With {.BackColor = Color.Blue, .IsBalloon = True, .ShowAlways = True} tt.SetToolTip(Button2, "Ok") tt.SetToolTip(TextBox1, "رمز") www.ali-arabi.com

  31. Structures, Enum : Public Class Form1 #Region "Declaration" Enum Weekday sat '= 2 sun mon tue wed thu fri End Enum Structure My_Date Dim y As Int16 Dim m, d As Byte End Structure Structure Student Dim name As String Dim bd As My_Date Dim salary As Single Dim holiday As Weekday End Structure #End Region Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim st As Student st.name = "ali" st.bd.y = 1369 st.salary = 3000000 st.holiday = Weekday.fri For w As Weekday = Weekday.sat To Weekday.thu st.salary += 100000 Next MsgBox(st.salary) End Sub End Class www.ali-arabi.com

  32. Collection : Structure Person Dim Name As String Dim Address As String End Structure Dim PhoneBook As New Collection Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim p As Person p.Name = "Ali" p.Address = "Tehran" PhoneBook.Add(p, "021 7689 9798") p.Name = "Reza" p.Address = "Mashhad" PhoneBook.Add(p, "0511 789 9798") For Each p In PhoneBook ListBox1.Items.Add(p.Name & "-" & p.Address) Next End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click If PhoneBook.Contains(TextBox1.Text) Then Dim p As Person = PhoneBook(TextBox1.Text) MsgBox(p.Name & "-" & p.Address) End If End Sub www.ali-arabi.com

  33. فایل های متنی با دسترسی ترتیبی : Private Sub Button1_Click(ByVal sender As System.Object, ByVal e . . . Dim f As Integer = FreeFile() FileOpen(f, "C:\a\test.txt", OpenMode.Output, OpenAccess.Write, OpenShare.LockRead) For i As Integer = 1 To 10 'Print(f, i) Write(f, "i=", i) Next FileClose(f) End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e . . . Dim f As Integer = FreeFile() Dim n As Integer, s As String = "" FileOpen(f, "C:\a\test.txt", OpenMode.Input) While Not EOF(f) Input(f, s) Input(f, n) ListBox1.Items.Add(s & n) End While FileClose(f) End Sub www.ali-arabi.com

  34. فایل های تصادفی با دسترسی مستقیم: Structure Person <VBFixedString(15)> Dim Name As String <VBFixedString(11)> Dim Tel As String End Structure Dim p As Person Private Sub Button1_Click(ByVal sender As System.Object, ByVal e . . . Dim f As Integer = FreeFile() p.Name = TextBox1.Text p.Tel = TextBox2.Text Dim lr As Integer = Len(p) FileOpen(f, "C:\a\test.dat", OpenMode.Random, OpenAccess.Write, OpenShare.LockWrite, Len(p)) Dim l As Long = LOF(f) / Len(p) 'Dim l As Long = FileLen("C:\a\test.txt") / Len(p) FilePut(f, p, l + 1) FileClose(f) End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e . . . Dim f As Integer = FreeFile() FileOpen(f, "C:\a\test.dat", OpenMode.Random, OpenAccess.Read, , Len(p)) FileGet(f, p, CLng(TextBox3.Text)) MsgBox(p.Name & vbNewLine & p.Tel) FileClose(f) End Sub www.ali-arabi.com

  35. گرافیک : Dim g As Graphics Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click g = Me.CreateGraphics() g.DrawRectangle(Pens.Coral, 10, 10, Me.Width - 30, Me.Height - 50) 'g.DrawArc(Pens.Black, 100, 100, 50, 100, 0, -90) 'g.DrawBezier(Pens.PaleGreen, 10, 10, 200, 10, 300, 200, 10, 10) 'g.DrawEllipse(Pens.Azure, 10, 10, Me.Width - 30, Me.Height - 50) 'Dim i As New Icon("c:\a\msn.ico") 'g.DrawIcon(i, 100, 100) 'g.DrawIcon(i, New Rectangle(10, 10, Me.Width - 30, Me.Height - 50)) 'g.DrawIconUnstretched(i, New Rectangle(10, 10, Me.Width - 30, Me.Height - 50)) 'g.DrawImage(Image.FromFile("c:\a\msn.ico"), New Point(10, 10)) Dim points() As Point = {New Point(10, 10), New Point(500, 10), New Point(250, 250), New Point(10, 10)} 'Dim pointstype() As Byte = {PathPointType.Line, PathPointType.Line, PathPointType.Line, PathPointType.Line} 'Dim p As New GraphicsPath(points, pointstype) 'g.DrawPath(Pens.Blue, p) 'g.DrawPie(Pens.Red, New Rectangle(10, 10, Me.Width - 30, Me.Height - 50), 0, -90) 'g.DrawPolygon(Pens.Blue, points) 'Dim b As New SolidBrush(Color.Aqua) 'Dim b As New LinearGradientBrush(New Point(10, 10), New Point(50, 50), Color.Blue, Color.Red) 'Dim b As New PathGradientBrush(points, WrapMode.Tile) 'g.FillRectangle(b, New Rectangle(10, 10, Me.Width - 30, Me.Height - 50)) 'Dim b As New HatchBrush(HatchStyle.Percent20, Color.Blue, Color.Red) 'Dim b As New TextureBrush(Image.FromFile("c:\a\watermark.bmp"), WrapMode.TileFlipXY) Dim b As SolidBrush = SystemBrushes.Highlight g.FillPolygon(b, points) End Sub www.ali-arabi.com

  36. Printing: Dim f As Integer Private Sub Button1_Click(ByVal sender As System.Object, ByVal e . . . PrintDialog1.Document = PrintDocument1 If PrintDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then PrintDocument1.PrinterSettings = PrintDialog1.PrinterSettings f = FreeFile() FileOpen(f, "c:\a\b.log", OpenMode.Input) PrintDocument1.Print() MsgBox("Printing Finished.") FileClose(f) End If End Sub Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e . . . Dim fnt As New Font("Arial", 14, FontStyle.Bold Or FontStyle.Italic) e.Graphics.DrawRectangle(Pens.Chocolate, e.MarginBounds) Dim x As Integer = e.MarginBounds.Left, y As Integer = e.MarginBounds.Top While Not EOF(f) Dim linestr As String = LineInput(f) e.Graphics.DrawString(linestr, fnt, Brushes.AliceBlue, x, y) y += fnt.GetHeight() If (y > e.MarginBounds.Bottom) Then Exit While End While If (y > e.MarginBounds.Bottom) Then e.HasMorePages = True Else e.HasMorePages = False End If End Sub www.ali-arabi.com

  37. فضای نام My : Dim s As Double = 0 For Each arg As String In My.Application.CommandLineArgs s += CDbl(arg) Next MsgBox(s) MsgBox(My.Application.Info.Description) MsgBox(My.Application.GetEnvironmentVariable("OS")) MsgBox(My.Computer.Screen.PrimaryScreen.WorkingArea.Height) MsgBox(My.Computer.Screen.Bounds.Height) MsgBox(My.Computer.Keyboard.CapsLock) My.Computer.Keyboard.SendKeys("{CAPSLOCK}") MsgBox(My.Computer.Info.OSFullName) MsgBox(My.Computer.Clock.LocalTime) TextBox2.Text = My.Computer.Clipboard.GetText PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage PictureBox1.Image = My.Computer.Clipboard.GetImage() www.ali-arabi.com

  38. کلاس Math : MsgBox(Math.Round(12.685, 2, MidpointRounding.AwayFromZero)) MsgBox(Math.Round(12.685, 2, MidpointRounding.ToEven)) MsgBox(Math.Round(12.675, 2, MidpointRounding.AwayFromZero)) MsgBox(Math.Round(12.675, 2, MidpointRounding.ToEven)) Dim A_D, A_R As Double A_D = 30 A_R = A_D * Math.PI / 180 MsgBox(Math.Sin(A_R)) Dim d, r As Integer d = Math.DivRem(100, 30, r) MsgBox(d & vbNewLine & r) www.ali-arabi.com

  39. مدیریت خطا (On Error , Err) : Dim x, y As Integer 'On Error Resume Next On Error GoTo l1 x = CInt(TextBox1.Text) y = CInt(TextBox2.Text) MsgBox(x \ y) MsgBox(x) Return l1: MsgBox(Err.Number & ": " & Err.Description) Resume Next 'Run MsgBox(x) ‘Resume 'Run MsgBox(x \ y) www.ali-arabi.com

  40. مدیریت خطا (Exception, Try…Catch…Finally) : Dim x, y As Integer Try x = CInt(TextBox1.Text) y = CInt(TextBox2.Text) MsgBox(x \ y) Catch ex As DivideByZeroException MsgBox("تقسیم بر صفر") 'MsgBox(Err.Number & ": " & Err.Description) Return Catch ex As InvalidCastException MsgBox("مقادیر عددی وارد کنید") Catch ex As Exception MsgBox(ex.Message) Finally MsgBox("Final") End Try www.ali-arabi.com

  41. پایگاه داده : Data و اشیاء مربوطه – ویزارد و کدنویسی : Imports System.Data.SqlClient Public Class Form1 Dim con As SqlConnection, da As SqlDataAdapter, dgv As DataGridView, ds As DataSet Private Sub Form1_Load(ByVal sender As System.Object, ByVal e . . . dgv = New DataGridView() With {.Parent = Me, .Dock = DockStyle.Fill} AddHandler dgv.SelectionChanged, AddressOf dgv_SelectionChanged con = New SqlConnection("server=site9-ostad; database=test;integrated security=true") 'Dim con As New SqlConnection("server=site9-ostad; database=test;user id=ali; password=123") اگر قبلا SqlCon را در Project->Windows Application Properties -> Settings از نوع Connection string تعریف کرده ایم 'Dim con As New SqlConnection(My.Settings("SqlCon")) Try con.Open() ds = New DataSet() da = New SqlDataAdapter("Select * From St_Info", con) da.Fill(ds, "St_Info") dgv.DataSource = ds dgv.DataMember = "St_Info" Catch ex As Exception MsgBox("Connection Not Open") Finally con.Close() End Try End Sub www.ali-arabi.com

  42. ادامه اسلاید قبلی ... Private Sub Insert_Click(ByVal sender As System.Object, ByVal e . . . con.Open() Dim sqlcmdins As SqlCommand 'sqlcmdins = New SqlCommand("Insert into st_info values(" & CLng(TextBox1.Text) & ",'" & TextBox2.Text & "','" & TextBox3.Text & "')", con) 'sqlcmdins = New SqlCommand("Insert Into st_info (St_ID,St_Name,St_Avg) values (" & CLng(TextBox1.Text) & ",'" & TextBox2.Text & "','" & TextBox3.Text & "')", con) sqlcmdins = New SqlCommand("Insert into st_info values(@id,@nam,@avg)", con) sqlcmdins.Parameters.AddWithValue("@id", TextBox1.Text) sqlcmdins.Parameters.AddWithValue("@nam", TextBox2.Text) sqlcmdins.Parameters.AddWithValue("@avg", TextBox3.Text) sqlcmdins.ExecuteNonQuery() con.Close() End Sub Private Sub dgv_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) If dgv.RowCount > 1 Then TextBox1.Text = dgv.CurrentRow.Cells(0).Value : TextBox2.Text = dgv.CurrentRow.Cells(1).Value TextBox3.Text = dgv.CurrentRow.Cells(2).Value End If End Sub Private Sub Del_Click(ByVal sender As System.Object, ByVal e . . . da = New SqlDataAdapter() da.DeleteCommand = New SqlCommand("Delete St_Info Where St_ID=" & CLng(TextBox1.Text), con) da.DeleteCommand.ExecuteNonQuery() con.Close() End Sub www.ali-arabi.com

  43. ادامه اسلاید قبلی ... Private Sub cmdRefresh_Click(ByVal sender As System.Object, ByVal e As . . . con.Open() ds.Tables("St_Info").Clear() da = New SqlDataAdapter("Select * From St_Info", con) da.Fill(ds, "St_info") con.Close() End Sub Private Sub cmdUpdate_Click(ByVal sender As System.Object, ByVal e As . . . con.Open() Dim sqlcmdupdate As SqlCommand sqlcmdupdate = New SqlCommand("Update st_info Set St_Name=@nam, St_Avg=@avg Where St_ID=@id", con) sqlcmdupdate.Parameters.AddWithValue("@id", TextBox1.Text) sqlcmdupdate.Parameters.AddWithValue("@nam", TextBox2.Text) sqlcmdupdate.Parameters.AddWithValue("@avg", TextBox3.Text) sqlcmdupdate.ExecuteNonQuery() con.Close() End Sub End Class www.ali-arabi.com

  44. نحوه Attach کردن یک Data Base : On Error Resume Next con.ConnectionString = "Server=. ;Database=Master; Integrated Security=True" con.Open() strSQL = "EXECUTE sp_attach_db @dbname = 'Students', @filename1 = 'C:\Students_Data.MDF', @filename2 = 'C:\Students_Log.LDF'" Comm.CommandText = strSQL Comm.ExecuteNonQuery() con.Close() con.ConnectionString = "Server=.; Database=Students; Integrated Security=True" con.Open() www.ali-arabi.com

  45. : Registry Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim n, f As String n = GetSetting("Info", "User1", "Name", "~!") f = GetSetting("Info", "User1", "Famil") 'Dim U As String(,) = GetAllSettings("Info", "User1") 'n = U(0, 1) : f = U(1, 1) If n = "~!" Then n = InputBox("Enter Name:") : f = InputBox("Enter Famil") SaveSetting("Info", "User1", "Name", n) SaveSetting("Info", "User1", "Famil", f) Else MsgBox("Hello " & n & " " & f) End If 'DeleteSetting("Info") 'DeleteSetting("Info", "User1") 'DeleteSetting("Info", "User1","Name") End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click My.Computer.Registry.CurrentUser.OpenSubKey("Console", True).SetValue("Test", 123) 'My.Computer.Registry.LocalMachine.SetValue("Test", 123, Microsoft.Win32.RegistryValueKind.DWord) MsgBox(My.Computer.Registry.CurrentUser.OpenSubKey("Console", True).GetValue("Test")) 'MsgBox(Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Console", True).GetValue("Test")) Dim reg As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.CurrentUser reg.OpenSubKey("AppEvents\EventLabels", True).SetValue("Test", 45) Dim p As Process() = Process.GetProcessesByName("Explorer") p(0).Kill() End Sub() www.ali-arabi.com

  46. کلاس ها : Public Function Pyramid() As Single Return 2 * Math.PI * Radius End Function Public Function Area() As Single Return Math.PI * Radius ^ 2 End Function Protected Overrides Sub Finalize() MsgBox(“ Destructor ") End Sub Sub New() ‘Constructor RadiusValue = 0 End Sub Sub New(ByVal R As Single) ‘Constructor RadiusValue = R End Sub End Class Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e . . . Try 'Dim c As New My_Circle(5) 'MsgBox(c.Radius) 'MsgBox(c.Pyramid()) 'MsgBox(c.Area()) Dim O As New My_Cylinder(10, 4) MsgBox(O.Area()) Catch ex As Exception MsgBox(ex.Message) End Try End Sub End Class Public Class My_Circle Private RadiusValue As Single 'Public Property Radius() As Single Public ReadOnly Property Radius() As Single Get Return RadiusValue End Get 'Set(ByVal value As Single) ' If value < 0 Then Throw New ApplicationException("Radius <0 !!!!!") ' R = value 'End Set End Property www.ali-arabi.com

  47. ادامه کلاس ها : Public Class My_Cylinder Inherits My_Circle Private HeightValue As Single Public Property Height() As Single Get Return HeightValue End Get Set(ByVal value As Single) HeightValue = value End Set End Property Sub New() MyBase.New(0) Height = 0 End Sub Sub New(ByVal Radius As Single, ByVal Height As Single) MyBase.New(Radius) MyClass.Height = Height End Sub Public Overloads Function Area() Return Height * Pyramid() + 2 * MyBase.Area End Function End Class www.ali-arabi.com

  48. کلاس پشته (Stack) : Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, . . . Dim s As New My_Stack For index As Integer = 1 To 10 s.Push(index) Next While Not s.Empty() ListBox1.Items.Add(s.Pop()) End While End Sub End Class Public Class Node Public avg As Single Public prev As Node End Class Public Class My_Stack Private top As Node Public Sub Push(ByVal a As Single) Dim newtop As New Node newtop.avg = a newtop.prev = top top = newtop End Sub Public Function Pop() Dim a As Single = top.avg top = top.prev Return a End Function Public Function Empty() If top Is Nothing Then Return True Else Return False End If End Function End Class www.ali-arabi.com

  49. : Class Library (DLL) Public Class My_Math Public Function Sin_D(ByVal d As Single) As Double Dim r As Single = d * Math.PI / 180 Return Math.Sin(r) End Function Public Function fact(ByVal x As Byte) As Double If x <= 1 Then Return 1 Else Return x * fact(x - 1) End Function End Class www.ali-arabi.com

  50. : User Control Library (DLL) Imports System.Drawing <ToolboxBitmap("C:\a\a.bmp")> _ Public Class My_Clock Public Event Time_M_Change As EventHandler Public Property Lable_B_C() As System.Drawing.Color Get Return Label1.BackColor End Get Set(ByVal value As System.Drawing.Color) Label1.BackColor = value End Set End Property Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e . . . Label1.Text = Now.Hour & ":" & Now.Minute & ":" & Now.Second If Now.Second = 59 Then RaiseEvent Time_M_Change(sender, e) End Sub End Class www.ali-arabi.com

More Related