-
گرفتن و تسخیر کردن (Capture) تصویر صفحه نمایش
کد:
https://barnamenevis.org/showpo...8&postcount=54
Private Function CaptureScreen() As Image
Dim screen As Bitmap = New Bitmap(Windows.Forms.Screen.PrimaryScreen.Bounds.W idth, Windows.Forms.Screen.PrimaryScreen.Bounds.Height)
Dim g As Graphics = Graphics.FromImage(screen)
Using (g)
g.CopyFromScreen(0, 0, 0, 0, screen.Size)
End Using
Return screen
End Function
-
پخش کردن برخی اصوات و صداهای سیستمی تنها با یک خط!
کد:
https://barnamenevis.org/showpo...9&postcount=55
'// Play a beep with default frequency
'// and duration (800 and 200, respectively)
Console.Beep()
'/ Play a beep with frequency as 200 and duration as 300
Console.Beep(200, 300)
Media.SystemSounds.Asterisk.Play()
Media.SystemSounds.Hand.Play()
Media.SystemSounds.Exclamation.Play()
Media.SystemSounds.Beep.Play()
Media.SystemSounds.Question.Play()
-
نواختن یک فایل صوتی با فرمت Wave
https://barnamenevis.org/showpo...5&postcount=56
Imports System.Media
Dim player As Media.SoundPlayer = New SoundPlayer()
Dim path As String = "C:\windows\media\ding.wav"
player.SoundLocation = path ' //Set the path
player.Play() ' //play it
-
بدست آوردن لیست چاپگرهای نصب شده در یک سیست
https://barnamenevis.org/showpo...7&postcount=57
Imports System.Drawing.Printing
Private Sub GetInstalledPrinters()
For Each printerName As String In PrinterSettings.InstalledPrinters
MessageBox.Show(printerName)
Next
End Sub
-
برخی اعمال متدوال روی تاریخ میلادی
https://barnamenevis.org/showpo...0&postcount=58
' // Create a TimeSpan representing 2.5 days.
Dim timespan1 As TimeSpan = New TimeSpan(2, 12, 0, 0)
'// Create a TimeSpan representing 4.5 days.
Dim timespan2 As TimeSpan = New TimeSpan(4, 12, 0, 0)
'// Create a TimeSpan representing 1 week.
Dim oneWeek As TimeSpan = timespan1 + timespan2
'// Create a DateTime with the current date and time.
Dim now As DateTime = DateTime.Now
'// Create a DateTime representing 1 week ago.
Dim past As DateTime = now - oneWeek
'// Create a DateTime representing 1 week in the future.
Dim future As DateTime = now + oneWeek
مثال : پیدا کردن اختلاف تعداد روزهای بین دو تاریخ :
کد:
Dim dateFrom As DateTime = DateTime.Parse("10/10/2007")
Dim dateTo As DateTime = DateTime.Parse("11/12/2007")
Dim ts As TimeSpan = dateTo - dateFrom
Dim days As Integer = ts.Days
و یا :
کد:
Dim dtFirst As DateTime = New DateTime(2007, 10, 10)
Dim dtSecond As DateTime = New DateTime(2007, 11, 12)
Dim diffResult As TimeSpan = dtSecond.Subtract(dtFirst)
-
تغییر خواص یک فایل
https://barnamenevis.org/showpo...3&postcount=59
Imports System.IO
Dim file As FileInfo = New FileInfo("C:\test.txt")
file.Attributes = file.Attributes Or FileAttributes.ReadOnly Or FileAttributes.Hidden
-
محاسبه ی حجم کلی یک دایرکتوری
https://barnamenevis.org/showpo...4&postcount=60
Imports System.IO
Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
MessageBox.Show(CalculateDirectorySize(New DirectoryInfo("C:\WINDOWS\System32"), True).ToString())
End Sub
Public Function CalculateDirectorySize(ByVal directory As DirectoryInfo, ByVal includeSubdirectories As Boolean) As Long
Dim totalSize As Long = 0
'// Examine all contained files.
Dim files() As FileInfo = directory.GetFiles()
For Each file As FileInfo In files
totalSize += file.Length
Next
' // Examine all contained directories.
If includeSubdirectories Then
Dim dirs() As DirectoryInfo = directory.GetDirectories()
For Each dir As DirectoryInfo In dirs
totalSize += CalculateDirectorySize(dir, True)
Next
End If
Return totalSize
End Function
-
خواندن و نوشتن رنگ یک پیکسل به کمک توابع API
https://barnamenevis.org/showpo...4&postcount=91
<DllImport("user32.dll")> _
Shared Function GetDC(ByVal hWnd As IntPtr) As IntPtr
End Function
<DllImport("user32.dll")> _
Shared Function ReleaseDC(ByVal hWnd As IntPtr, ByVal hDC As IntPtr) As Integer
End Function
<DllImport("gdi32.dll")> _
Shared Function GetPixel(ByVal hDC As IntPtr, ByVal x As Integer, ByVal y As Integer) As Integer
End Function
<DllImport("gdi32.dll")> _
Shared Function SetPixel(ByVal hDC As IntPtr, ByVal x As Integer, ByVal y As Integer, ByVal color As Integer) As Integer
End Function
Public Shared Function GetPixel(ByVal control As Control, ByVal x As Integer, ByVal y As Integer) As Color
Dim color As Color = color.Empty
If Not control Is Nothing Then
Dim hDC As IntPtr = GetDC(control.Handle)
Dim colorRef As IntPtr = GetPixel(hDC, x, y)
color = color.FromArgb((colorRef.ToInt32 & &HFF) Or (colorRef.ToInt32 & &HFF00 >> 8) Or (colorRef.ToInt32 & &HFF0000 >> 16))
ReleaseDC(control.Handle, hDC)
End If
Return color
End Function
Public Shared Sub SetPixel(ByVal control As Control, ByVal x As Integer, ByVal y As Integer, ByVal color As Color)
If Not control Is Nothing Then
Dim hDC As IntPtr = GetDC(control.Handle)
Dim argb As Integer = color.ToArgb()
Dim colorRef As Integer = ((argb & &HFF0000) >> 16) Or (argb & &HFF00) Or ((argb & &HFF) << 16)
SetPixel(hDC, x, y, colorRef)
ReleaseDC(control.Handle, hDC)
End If
End Sub
-
تبدیل اتوماتیک دکمه Enter به Tab جهت انتقال فوکوس در کنترلها
منبع:https://barnamenevis.org/showpo...66&postcount=4
این کد را در کلاس مربوط به کنترل TextBox خود بنویسید :
کد:
Protected Overrides Function ProcessDialogKey(ByVal keyData As System.Windows.Forms.Keys) As Boolean
If keyData = Keys.Return Then
SendKeys.Send("{TAB}")
End If
Return MyBase.ProcessDialogKey(keyData)
End Function
و در مورد استفاده در کنترلهای استاندارد :
کد:
Private Sub TextBox1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
If e.KeyCode = Keys.Return Then
SendKeys.Send("{TAB}")
End If
End Sub
-
خواندن و نوشتن فایلهای متنی
https://barnamenevis.org/showpo...6&postcount=61
Imports System.IO
Private Sub CreateTextFile()
Dim fs As FileStream = New FileStream("C:\test.txt", FileMode.Create)
Dim w As StreamWriter = New StreamWriter(fs, Encoding.UTF8)
Using (fs)
Using (w)
w.WriteLine(124.23)
w.WriteLine("Salaam!")
w.WriteLine("!")
End Using
End Using
End Sub
Private Function ReadFromTextFile() As String
Dim sb As StringBuilder = New StringBuilder()
Dim fs As FileStream = New FileStream("C:\test.txt", FileMode.Open)
Dim r As StreamReader = New StreamReader(fs, Encoding.UTF8)
Using (fs)
Using (r)
sb.AppendLine(r.ReadLine())
sb.AppendLine(r.ReadLine())
sb.AppendLine(r.ReadLine())
End Using
End Using
Return sb.ToString()
End Function
-
اضافه و جدا کردن نام فایل از مسیر کامل
https://barnamenevis.org/showpo...7&postcount=62
Dim filename As String = "..\..\myfile.txt"
Dim fullPath As String = "c:\Temp"
Dim filename As String = Path.GetFileName(filename)
Dim fullPath As String = Path.Combine(fullPath, filename)
'// (fullPath is now "c:\Temp\myfile.txt")
-
ایجاد یک نام تصادفی برای فایل
https://barnamenevis.org/showpo...8&postcount=63
Dim randomFileName As String = System.IO.Path.GetRandomFileName()
و برای ایجاد نام منحصر بفرد برای فایلهای موقت :
کد:
Dim tfile As String = Path.GetTempFileName()
-
باز کردن یک سایت توسط internet explorer
https://barnamenevis.org/showpo...0&postcount=64
System.Diagnostics.Process.Start("iexplore.exe", "www.barnamenevis.org")
و برای مثال در فایرفاکس :
کد:
System.Diagnostics.Process.Start("C:\Program Files\Mozilla Firefox\FireFox.exe", "www.barnamenevis.org")
-
تبدیل نوع enum به int
https://barnamenevis.org/showpo...8&postcount=65
Public Enum Days
Sat = 1
Sun
Mon
Tue
Wed
Thu
Fri
End Enum
Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim x As Integer = Days.Mon
End Sub
-
انتقال آیتمهای Enum به یک ListBox
https://barnamenevis.org/showpo...1&postcount=66
Public Enum Days
Sat = 1
Sun
Mon
Tue
Wed
Thu
Fri
End Enum
Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim t As System.Type = GetType(Days)
For Each s As String In Days.GetNames(t)
ListBox1.Items.Add(s)
Next
End Sub
-
معرفی میانبرهای متداول در کدنویسی
عادت کردن به میانبرها میتواند سرعت کدنویسی شما را افزایش دهد :
https://barnamenevis.org/showpo...6&postcount=67
-
بدست آوردن لیست تمامی فرمهای باز در یک برنامه
https://barnamenevis.org/showpo...6&postcount=68
مثال : تغییر رنگ پشت زمینه ی تمامی فرمهای باز در یک برنامه :
For Each frm As Form In Application.OpenForms
frm.BackColor = Color.Fuchsia
Next
-
restart کردن (بستن و مجددا اجرا کردن) برنامه
-
ساده ترین راه برای جلوگیری از Not Respond شدن برنامه در حلقه های طولانی
https://barnamenevis.org/showpo...8&postcount=70
برنامه تمامی message های درون message queue فعلی (از قبیل رخدادها و ...) را پردازش میکند.
کد:
Application.DoEvents()
-
فقط یک نمونه از برنامه بتواند اجرا شود (با استفاده از Process)
https://barnamenevis.org/showpo...7&postcount=71
این تغییرات را در کلاس مربوط به StartUp برنامه اعمال کنید :
کد:
Imports System.Diagnostics
Class Program
<STAThread()> _
Shared Sub Main()
If IsPrevInstance() Then
Return
End If
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(Fals e)
Application.Run(New Form1())
End Sub
Private Shared Function IsPrevInstance() As Boolean
Dim processName As String = Process.GetCurrentProcess().ProcessName
Dim instances() As Process = Process.GetProcessesByName(processName)
If instances.Length > 1 Then
Return True
Else
Return False
End If
End Function
End Class
-
روش ارسال ایمیل به چندین گیرنده
https://barnamenevis.org/showpo...1&postcount=78
Imports System.Net.Mail
Class SendEmail
Public Shared Sub SendMessage(ByVal subject As String, ByVal messageBody As String, ByVal fromAddress As String, ByVal toAddress As String, ByVal ccAddress As String)
Dim message As MailMessage = New MailMessage()
Dim client As SmtpClient = New SmtpClient()
message.From = New MailAddress(fromAddress)
'// Allow multiple "To" addresses to be separated by a semi-colon
If toAddress.Trim().Length > 0 Then
For Each addr As String In toAddress.Split(";")
message.To.Add(New MailAddress(addr))
Next
End If
'// Allow multiple "Cc" addresses to be separated by a semi-colon
If ccAddress.Trim().Length > 0 Then
For Each addr As String In ccAddress.Split(";")
message.CC.Add(New MailAddress(addr))
Next
End If
message.Subject = subject
message.Body = messageBody
client.Host = "YourMailServer"
client.Send(message)
End Sub
End Class
-
نحوه Drag کردن عکس از یک pictureBox به یک pictureBox دیگه
https://barnamenevis.org/showpo...5&postcount=79
برای این عمل به یک رویداد (MouseMove) برای pictureBox منبع نیاز دارید و دو رویداد (DragDrop) و ( DragEnter) از pictureBox مقصد. که نحوه کد کردن آن ها به شکل زیر است
Private Sub PictureBox1_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
If e.Button = MouseButtons.Left And Not PictureBox1.Image Is Nothing Then
PictureBox1.DoDragDrop(PictureBox1.Image, DragDropEffects.All)
End If
End Sub
Private Sub PictureBox2_DragEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles PictureBox2.DragEnter
If e.Data.GetDataPresent(DataFormats.Bitmap) Then
e.Effect = DragDropEffects.Copy
Else
e.Effect = DragDropEffects.None
End If
End Sub
Private Sub PictureBox2_DragDrop(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles PictureBox2.DragDrop
If e.Data.GetDataPresent(DataFormats.Bitmap) Then
PictureBox1.Image = CType(e.Data.GetData(DataFormats.Bitmap), Image)
End If
End Sub
نکته : خاصیت AllowDrop مربوط به pictureBox مقصد را بایستی true کنید. دقت داشته باشید که این خاصیت، در پنجره خواص مربوط به pictureBox وجود نداره و باید اونو از طریق کد نویسی اعمال کنید.
-
نحوه ایجاد فرم About بدون کد نویسی و طراحی فرم
-
سیاه و سفید کردن عکس با کد نویسی
https://barnamenevis.org/showpo...1&postcount=81
توسط متد زیر می توانید هر عکسی را به حالت سیاه و سفید یا همون grayScale در بیارین
کد:
Imports System.Drawing.Imaging
Public Function GrayScaleImage(ByVal graph As Graphics, ByVal img As Image, ByVal left As Integer, ByVal top As Integer) As Image
Dim colorMix As ColorMatrix = New ColorMatrix()
colorMix.Matrix00 = 1 / 3.0F
colorMix.Matrix01 = 1 / 3.0F
colorMix.Matrix02 = 1 / 3.0F
colorMix.Matrix10 = 1 / 3.0F
colorMix.Matrix11 = 1 / 3.0F
colorMix.Matrix12 = 1 / 3.0F
colorMix.Matrix20 = 1 / 3.0F
colorMix.Matrix21 = 1 / 3.0F
colorMix.Matrix22 = 1 / 3.0F
Dim imgAttrib As ImageAttributes = New ImageAttributes()
imgAttrib.SetColorMatrix(colorMix)
graph.DrawImage(img, New Rectangle(left, top, img.Width, img.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, imgAttrib)
Dim bmp As Bitmap = New Bitmap(img)
Return bmp
End Function
-
کار کردن با کلاس TimeZoneInfo
https://barnamenevis.org/showpo...0&postcount=82
این کلاس مختص دات نت 3.5 (به بعد) است و جهت استفاده باید System.Core رو نیز به References پروژه ی خود بیافزایید.
مثال - بدست آوردن تاریخ و زمان فعلی در توکیو :
کد:
Dim tzSource As TimeZoneInfo = TimeZoneInfo.Local
Dim tzDestination As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time")
Dim sourceTime As String = TimeZoneInfo.ConvertTime(DateTime.Now, tzSource, tzDestination).ToShortTimeString()
MessageBox.Show(sourceTime)
-
بدست آوردن لیست تمامی ناحیه های زمانی (Time Zone)
https://barnamenevis.org/showpo...1&postcount=83
این روش مختص دات نت 3.5 (به بعد) است.
کد:
Imports System.Collections.ObjectModel
بدست آوردن Id و DisplayName نواحی :
کد:
Dim zones As ReadOnlyCollection(Of TimeZoneInfo) = TimeZoneInfo.GetSystemTimeZones()
For Each zone As TimeZoneInfo In zones
ListBox1.Items.Add(zone.Id)
listBox2.Items.Add(zone.DisplayName)
Next
-
انجام عملیات متداول روی فایلها و دایرکتوریها
https://barnamenevis.org/showpo...3&postcount=84
Imports System.IO
'//To create a directory
Directory.CreateDirectory("C:\MyNewDir")
'//To move a directory
Directory.Move("C:\MyNewDir", "C:\MyMovedDir")
'//To delete a directory
Directory.Delete("C:\MyMovedDir")
'//To Delete a directory recursively
Directory.Delete("C:\MyNewDir", True)
'//To Delete a File
File.Delete("C:\MyFile.Txt")
'//To Move a File
File.Move("C:\MyFile.Txt", "C:\MyOtherDir\MyFile.Txt")
'//To Copy a file
File.Copy("C:\MyFile.Txt", "C:\MyOtherDir\MyFile.Txt")
'//To copy to a different file name is also possible
File.Copy("C:\MyFile.Txt", "C:\MyOtherDir\MyNewFileName.Txt")
'//To get information about a file, like the length
'//You can also get the extension, directory, LastAccessedtime,
'//LastModifiedTime, wether the file exists or not, the creation date,
'//attributes of the file etc, from the FileInfo class
Dim FI As FileInfo = New FileInfo("C:\MyFile.Txt")
Console.WriteLine("File size of MyFile.Txt: {0}", FI.Length)
'//copy example
Dim DateTemp As String = DateTime.Now.ToString
File.Copy("P:\PRD\Products\AHM\prod.CD\Database\da ta.mdb", "P:\PRD\Products\AHM\prod.CD\Database\" + DateTemp + "-data.mdb")
-
کپی کردن فایلهای درون یک دایرکتوری (فقط فایلها)
https://barnamenevis.org/showpo...3&postcount=86
فایلها را در مسیرC:\CopiedFolder کپی میکند :
کد:
Imports System.IO
Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim fbd As FolderBrowserDialog = New FolderBrowserDialog()
fbd.Description = "Find Folder to Copy."
If fbd.ShowDialog() = DialogResult.OK Then
Dim files() As String = Directory.GetFiles(fbd.SelectedPath)
Directory.CreateDirectory("C:\CopiedFolder")
Dim i As Integer
For i = 0 To files.Length
Dim tmpFileExt As String = Path.GetExtension(files(i))
Dim tmpFileName As String = Path.GetFileNameWithoutExtension(files(i))
File.Copy(files(i), "C:\CopiedFolder\" + tmpFileName + tmpFileExt, True)
Next
End If
End Sub
-
کپی کامل یک دایرکتوری و تمامی زیرشاخه های آن بصورت بازگشتی
https://barnamenevis.org/showpo...9&postcount=88
Imports System.IO
Sub CopyDirectory(ByVal source As DirectoryInfo, ByVal destination As DirectoryInfo)
If Not destination.Exists Then
destination.Create()
End If
'// Copy all files.
Dim files() As FileInfo = source.GetFiles()
For Each file As FileInfo In files
file.CopyTo(Path.Combine(destination.FullName, file.Name))
Next
'// Process subdirectories.
Dim dirs() As DirectoryInfo = source.GetDirectories()
For Each dir As DirectoryInfo In dirs
' // Get destination directory.
Dim destinationDir As String = Path.Combine(destination.FullName, dir.Name)
'// Call CopyDirectory() recursively.
CopyDirectory(dir, New DirectoryInfo(destinationDir))
Next
End Sub
-
انجام عملیات متداول در رجیستری ویندوز
https://barnamenevis.org/showpo...4&postcount=93
Imports Microsoft.Win32
Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
' // Create SubKey
Registry.LocalMachine.CreateSubKey("Software\Sinpi n", RegistryKeyPermissionCheck.ReadWriteSubTree)
'//Create Key and Set Value
Dim reg As RegistryKey = Registry.LocalMachine.OpenSubKey("Software\Sinpin" , True)
reg.SetValue("DWord", "1", RegistryValueKind.DWord)
reg.SetValue("ExpandString", "1", RegistryValueKind.ExpandString)
reg.SetValue("QWord", "1", RegistryValueKind.QWord)
reg.SetValue("String", "1", RegistryValueKind.String)
reg.SetValue("Unknown", "1", RegistryValueKind.Unknown)
'// Delete Key
reg.DeleteValue("DWOrd")
'// Delete SubKey
Registry.LocalMachine.DeleteSubKey("Software\Sinpi n")
'// Read Key Value
Dim val As String = reg.GetValue("QWord").ToString()
'// Retrieve All Keys
For Each s As String In reg.GetValueNames()
MessageBox.Show(s)
Next
End Sub
-
Resize کردن یک تصویر با کدنویسی
https://barnamenevis.org/showpo...3&postcount=94
Imports System.Drawing.Drawing2D
Private Shared Function resizeImage(ByVal imgToResize As Image, ByVal size As Size) As Image
Dim sourceWidth As Integer = imgToResize.Width
Dim sourceHeight As Integer = imgToResize.Height
Dim nPercent As Decimal = 0
Dim nPercentW As Decimal = 0
Dim nPercentH As Decimal = 0
nPercentW = (size.Width / sourceWidth)
nPercentH = size.Height / sourceHeight
If nPercentH < nPercentW Then
nPercent = nPercentH
Else
nPercent = nPercentW
End If
Dim destWidth As Integer = (sourceWidth * nPercent)
Dim destHeight As Integer = (sourceHeight * nPercent)
Dim b As Bitmap = New Bitmap(destWidth, destHeight)
Dim g As Graphics = Graphics.FromImage(b)
g.InterpolationMode = InterpolationMode.HighQualityBicubic
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight)
g.Dispose()
Return b
End Function
-
Crop کردن یک تصویر (یک برش مستطیلی از تصویر)
https://barnamenevis.org/showpo...9&postcount=95
Private Shared Function cropImage(ByVal img As Image, ByVal cropArea As Rectangle) As Image
Dim bmpImage As Bitmap = New Bitmap(img)
Dim bmpCrop As Bitmap = bmpImage.Clone(cropArea, bmpImage.PixelFormat)
Return (bmpCrop)
End Function
مثال از نحوه ی استفاده :
کد:
Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
PictureBox2.Image = cropImage(PictureBox1.Image, New Rectangle(10, 10, 100, 100))
End Sub
-
تبدیل یک تصویر رنگی به معادل GrayScal آن
https://barnamenevis.org/showpo...9&postcount=96
Imports System.Drawing.Imaging
Public Shared Function MakeGrayscale(ByVal original As Bitmap) As Bitmap
' //create a blank bitmap the same size as original
Dim newBitmap As Bitmap = New Bitmap(original.Width, original.Height)
'//get a graphics object from the new image
Dim g As Graphics = Graphics.FromImage(newBitmap)
'//create the grayscale ColorMatrix
Dim array()() As Single = New Single()() {New Single() {0.3F, 0.3F, 0.3F, 0, 0}, _
New Single() {0.59F, 0.59F, 0.59F, 0, 0}, _
New Single() {0.11F, 0.11F, 0.11F, 0, 0}, _
New Single() {0, 0, 0, 1, 0}, _
New Single() {0, 0, 0, 0, 1}}
Dim colorMatrix As ColorMatrix = New ColorMatrix(array)
'//create some image attributes
Dim attributes As ImageAttributes = New ImageAttributes()
'//set the color matrix attribute
attributes.SetColorMatrix(colorMatrix)
'//draw the original image on the new image
'//using the grayscale color matrix
g.DrawImage(original, New Rectangle(0, 0, original.Width, _
original.Height), 0, 0, original.Width, _
original.Height, GraphicsUnit.Pixel, attributes)
'//dispose the Graphics object
g.Dispose()
Return newBitmap
End Function
Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim b As Bitmap = PictureBox1.Image
PictureBox2.Image = MakeGrayscale(b)
End Sub
-
بدست آوردن مقدار یک Enum از عدد متناظر آن
https://barnamenevis.org/showpo...4&postcount=97
Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim day As Integer = 3
Dim d As DaysOfWeek = NumToEnum(Of DaysOfWeek)(day)
MsgBox(d.ToString)
End Sub
Public Function NumToEnum(Of T)(ByVal number As Integer) As T
Return [Enum].ToObject(GetType(T), number)
End Function
Public Enum DaysOfWeek
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
End Enum
-
بدست آوردن مقدار یک Enum از رشته متنی متناظر با آن
https://barnamenevis.org/showpo...7&postcount=98
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim d As DaysOfWeek = StringToEnum(Of DaysOfWeek)("Monday")
'//d is now DaysOfWeek.Monday
MsgBox(d.ToString)
If [Enum].IsDefined(GetType(DaysOfWeek), "Katillsday") Then
StringToEnum(Of DaysOfWeek)("Katillsday")
End If
End Sub
Public Shared Function StringToEnum(Of T)(ByVal name As String) As t
Return [Enum].Parse(GetType(T), name)
End Function
Public Enum DaysOfWeek
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
End Enum
-
چرخاندن یک تصویر با زاویه دلخواه
https://barnamenevis.org/showpo...&postcount=100
Private Function rotateImage(ByVal b As Bitmap, ByVal angle As Single) As Bitmap
' //create a new empty bitmap to hold rotated image
Dim returnBitmap As Bitmap = New Bitmap(b.Width, b.Height)
'//make a graphics object from the empty bitmap
Dim g As Graphics = Graphics.FromImage(returnBitmap)
'//move rotation point to center of image
g.TranslateTransform(b.Width / 2, b.Height / 2)
'//rotate
g.RotateTransform(angle)
'//move image back
g.TranslateTransform(-b.Width / 2, -b.Height / 2)
'//draw passed in image onto graphics object
g.DrawImage(b, New Point(0, 0))
Return returnBitmap
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim b As Bitmap = PictureBox1.Image
PictureBox2.Image = rotateImage(b, 60)
End Sub
-
ارسال تعداد متغیر پارامتر به یک متود
https://barnamenevis.org/showpo...&postcount=101
با استفاده از کلمه کلیدی params مانند نمونه زیر :
کد:
Public Function Add(ByVal list() As Integer) As Integer
Dim sum As Integer = 0
For Each i As Integer In list
sum += i
Next
Return sum
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim ans2 As Integer = Add(New Integer() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
End Sub
-
Serialize کردن باینری آبجکت در فایل
https://barnamenevis.org/showpo...&postcount=102
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary
Public Sub SerializeObject(ByVal filename As String, ByVal o As Object)
Dim stream As Stream = File.Open(filename, FileMode.Create)
Dim bFormatter As BinaryFormatter = New BinaryFormatter()
bFormatter.Serialize(stream, o)
stream.Close()
End Sub
-
Serialize کردن object در XML
https://barnamenevis.org/showpo...&postcount=105
برای Serialize کردن یک object در فایل XML می تونین از این کد استفاده کنین:
کد:
Imports System.Xml.Serialization
Dim xmSer As XmlSerializer = New XmlSerializer(GetType(Person))
Dim st As FileStream = New FileStream("C:\Test.xml", FileMode.OpenOrCreate)
Dim p As Person = New Person("Ali Rezaei", 44)
xmSer.Serialize(st, p)
st.Close()
-
DeSerialize کردن object از XML
https://barnamenevis.org/showpo...&postcount=106
Imports System.Xml.Serialization
Dim xmSer As XmlSerializer = New XmlSerializer(GetType(Person))
Dim st As FileStream = New FileStream("C:\Test.xml", FileMode.Open)
Dim p As Person = xmSer.Deserialize(st)
st.Close()
-
Serialize کردن object در SOAP XML
https://barnamenevis.org/showpo...&postcount=107
برای Serialize کردن object تون توی فایل Soap می تونین از این کد استفاده کنین.
دقت کنین که باید System.Runtime.Serialization.Formatters.Soap رو Add Reference و Imports کنین.
کد:
Imports System.Runtime.Serialization.Formatters.Soap
Dim soap As SoapFormatter = New SoapFormatter()
Dim st As FileStream = New FileStream("C:\Test.soap", FileMode.OpenOrCreate)
Person(p = New Person("Ali Rezaei", 33))
soap.Serialize(st, p)
st.Close()
-
DeSerialize کردن object از SOAP XML
https://barnamenevis.org/showpo...&postcount=108
برای بازیابی شیء تون از یک فایل SOAP می تونین از این کد استفاده کنین:
کد:
Dim soap As SoapFormatter = New SoapFormatter()
Dim st As FileStream = New FileStream("C:\Test.soap", FileMode.Open)
p = soap.Deserialize(st)
st.Close()
-
تعریف عملگر های سفارشی
https://barnamenevis.org/showpo...&postcount=109
Class newClass
Private number As Integer
Public Sub New(ByVal _number As Integer)
Me.number = _number
End Sub
Public Overloads Shared Operator +(ByVal c1 As newClass, ByVal c2 As newClass) As newClass
Return New newClass(c1.number + c2.number)
End Operator
End Class
تعریف یک Operator overloading همیشه باید بصورت shared و Public باشد و مقدار برگشتی آن نیز نمیتواند nothing باشد.
-
بدست آوردن شماره سریال پراسسور (CPU Id)
https://barnamenevis.org/showpo...&postcount=111
ابتدا System.Management رو به References پروژه بیفزایید و سپس :
کد:
Imports System.Management
Public Shared Function GetCPUId() As String
Dim cpuInfo As String = String.Empty
'//create an instance of the Managemnet class with the
'//Win32_Processor class
Dim mgmt As ManagementClass = New ManagementClass("Win32_Processor")
'//create a ManagementObjectCollection to loop through
Dim objCol As ManagementObjectCollection = mgmt.GetInstances()
'//start our loop for all processors found
For Each obj As ManagementObject In objCol
If cpuInfo = String.Empty Then
'// only return cpuInfo from first CPU
cpuInfo = obj.Properties("ProcessorId").Value.ToString()
End If
Next
Return cpuInfo
End Function
-
DeSerialize کردن باینری آبجکت از فایل
https://barnamenevis.org/showpo...&postcount=112
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Xml.Serialization
Public Function DeSerializeObject(ByVal filename As String) As Object
Dim o As Object
Dim stream As Stream = File.Open(filename, FileMode.Open)
Dim bFormatter As BinaryFormatter = New BinaryFormatter()
o = bFormatter.Deserialize(stream)
stream.Close()
Return o
End Function
-
بدست آوردن نام شرکت سازنده پراسسور (CPU Manufacturer)
https://barnamenevis.org/showpo...&postcount=113
ابتدا System.Management رو به References پروژه بیفزایید و سپس :
کد:
Imports System.Management
Public Function GetCPUManufacturer() As String
Dim cpuMan As String = String.Empty
'//create an instance of the Managemnet class with the
'//Win32_Processor class
Dim mgmt As ManagementClass = New ManagementClass("Win32_Processor")
'//create a ManagementObjectCollection to loop through
Dim objCol As ManagementObjectCollection = mgmt.GetInstances()
'//start our loop for all processors found
For Each obj As ManagementObject In objCol
If cpuMan = String.Empty Then
' // only return manufacturer from first CPU
cpuMan = obj.Properties("Manufacturer").Value.ToString()
End If
Next
Return cpuMan
End Function
-
بدست آوردن میزان فضای خالی یک درایو (پارتیشن)
https://barnamenevis.org/showpo...&postcount=114
Imports System.Management
Public Function GetHDDFreeSpace(ByVal drive As String) As Double
' //check to see if the user provided a drive letter
' //if not default it to "C"
If drive = "" Or drive Is Nothing Then
drive = "C"
End If
'//create our ManagementObject, passing it the drive letter to the
'//DevideID using WQL
Dim disk As ManagementObject = New ManagementObject("Win32_LogicalDisk.DeviceID=""" + drive + ":\""")
'//bind our management object
disk.Get()
'//return the free space amount
Return Convert.ToDouble(disk("FreeSpace"))
End Function
-
بدست آوردن حجم کلی یک درایو (پارتیشن)
https://barnamenevis.org/showpo...&postcount=115
ابتدا System.Management رو به References پروژه بیفزایید و سپس :
کد:
Imports System.Management
Public Function getHDDSize(ByVal drive As String) As Double
' //check to see if the user provided a drive letter
' //if not default it to "C"
If drive = "" Or drive Is Nothing Then
drive = "C"
End If
'//create our ManagementObject, passing it the drive letter to the
'//DevideID using WQL
Dim disk As ManagementObject = New ManagementObject("Win32_LogicalDisk.DeviceID=""" + drive + ":\""")
'//bind our management object
disk.Get()
'//return the HDD's initial size
Return Convert.ToDouble(disk("Size"))
End Function
-
چرا و کی باید از کلاس StringBuilder به جای string استفاده کنیم ؟
https://barnamenevis.org/showpo...&postcount=116
آبجکتهای string در دات نت immutable (غیرقابل تغییر) هستند :به این معنا که پس از مقدار گرفتن، دیگر قابل تغییر نیستند.
به مثال زیر دقت کنید :
کد:
Dim temp As String = "a"
temp = temp + "b"
temp += "c"
temp += "d
"
در این مثال ابتدا یک آبجکت از نوع string میسازید، اما در خطوط بعدی با هر بار تغییر مقدار آن؛ آبجکتهای قدیمی فراموش و یک آبجکت جدید از نوع string - با مقدار جدید - ساخته میشود.
به این ترتیب میشه انتظار داشت که کد زیر چه سربار وحشتناکی روی منابع سیستم میتونه داشته باشه :
کد:
Dim s2 As String = New String("x", Int32.Parse(args(0)))
Dim loops As Integer = Int32.Parse(args(1))
Dim j, i As Integer
For j = 0 To 10000000
Dim s As String = ""
For i = loops To 0 Step -1
s += s2
Next
Next
بصورت کلی در حالتیکه اعمال تغییرات زیاد روی رشته ها نیاز باشد بهتر است آبجکتی از کلاس StringBuilder ساخته و با خاصیت Append آن کار کنیم.
مثال - پیاده سازی همان کد قبلی :
کد:
Dim s2 As String = New String("x", Int32.Parse(args(0)))
Dim loops As Integer = Int32.Parse(args(1))
Dim i, j As Integer
For j = 0 To 10000000
Dim sb As StringBuilder = New StringBuilder()
For i = loops To 0 Step -1
sb.Append(s2)
Next
sb.ToString()
Next
-
ساختن یک لیست ژنریک از اشیاء
https://barnamenevis.org/showpo...&postcount=117
با فرض داشتن کلاسی مانند :
کد:
Public Class Person
Public Sub New(ByVal _firstName As String, ByVal _lastName As String)
Me.FirstName = _firstName
Me.lastName = _lastName
End Sub
Private _firstName As String
Public Property FirstName() As String
Get
Return _firstName
End Get
Set(ByVal value As String)
_firstName = value
End Set
End Property
Private _lastName As String
Public Property LastName() As String
Get
Return _lastName
End Get
Set(ByVal value As String)
_lastName = value
End Set
End Property
End Class
میتونیم بنویسیم :
کد:
Dim persons As List(Of Person) = New List(Of Person)
persons.Add(New Person("ali", "ahmadi"))
persons.Add(New Person("maryam", "hosseini"))