-
فرستادن کلیدهای ترکیبی با SendKeys (به صورت کامل)
با سلام
سال نو رو به شما دوستان عزیز تبریک عرض میکنم
با اجازه از آقای غقوری
این پست در واقع کامل کننده ی پست قبلی (پست آقای غفوری) هست
------------------------------------------------------------------------------
در صورتی که بخواهید بدون فشردن یک کلید از کیبورد کاری کنید که یک کلید خاص فشرده بشه میتونید از این دستور به صورت زیر استفاده میکنید :
((دقت کنید که هیچ تفاوتی بین فشردن یک کلید رو کیبورد و دستور sendkeys وجود نداره))
SendKeys String[,wait]
String : رشته ای که در واقع همون نویسه هایی هست که باید به عنوان کلید ارسال بشن
Wait : پارامتری منطقی است. اگر روی False تنظیم بشه (پیش فرض) ، روال اجرا کننده دستور Sendkeys بلافاصله بعد از ارسال نویسه ها مجددا کنترل برنامه رو در دست میگیره و به کار خودش ادامه میده. اما اگه رو True تنظیم بشه سیستم تا پردازش کامل نویسه ها ، کنترل رو به روال اجرا کننده ی دستور Sendkeys باز پس نمیده
توجه کنید که برای ارسال نویسه های خاص (~ , { , } , % , ( , ) , - , + , ^) باید اونا رو داخل {} قرار بدیم
به عنوال مثال :
SendKyes "+ {+} 4 {*} 6
کلیدهای ویژه در دستور Sendkeys :
- کلید TAB : معادل {TAB}
- کلید UP ARROW : معادل {UP}
- کلید F1 : معادل {F1}
- کلید F2 : معادل {F2}
- کلید F3 : معادل {F3}
- کلید F4 : معادل {F4}
- کلید F5 : معادل {F5}
- کلید F6 : معادل {F6}
- کلید F7 : معادل {F7}
- کلید F8 : معادل {F8}
- کلید F9 : معادل {F9}
- کلید F10 : معادل {F10}
- کلید F11 : معادل {F11}
- کلید F12 : معادل {F12}
- کلید F13 : معادل {F13}
- کلید F14 : معادل {F14}
- کلید F15 : معادل {F15}
- کلید F16 : معادل {F16}
- کلید BACKSPACE: معادل {BACKSPACE} یا {BS} یا {BKSP}
- کلید BREAK : معادل {BREAK}
- کلید CAPS LOCK : معادل {CAPSLOCK}
- کلید DELETE یا DEL : معادل {DELETE} یا {DEL}
- کلید DOWN ARROW : معادل {DOWN}
- کلید END : معادل {END}
- کلید ENTER : معادل {ENTER} یا {~}
- کلید ESC : معادل {ESC}
- کلید HELP : معادل {HELP}
- کلید HOME : معادل {HOME}
- کلید INS یا INSERT : معادل {INSERT} یا {INS}
- کلید LEFT ARROW : معادل {LEFT}
- کلید NUM LOCK : معادل {NUMLOCK}
- کلید PAGE DOWN : معادل {PGDN}
- کلید PAGE UP : معادل {PGUP}
- کلید PRINT SCREEN : معادل {PRTSC}
- کلید RIGHT ARROW : معادل {RIGHT}
- کلید SCROLL LOCK : معادل {SCROLLLOCK}
توجه کنید که تنها کلیدی که نمیتونیم اون رو به برنامه ها بفرستیم ، کلید Print Screen هست (شماره ی 34)
برای استفاده از کلید های Alt , Ctrl , Shift همون طور که آقای غفوری گفتند میتونید از معادل های زیر استفاده کنید
- کلید Shift : معادل {+}
- کلید Ctrl : معادل {^}
- کلید Alt : معادل {%}
به عنوان مثال :
Sendkeys "+(ES)"
یعنی فشردن کلید Shift به همراه کلید های E , S
Sendkeys "+ES"
یعنی فشرن کلید Shift به همراه E و پس از رها کردن ، فشردن کلید S است
توجه : اگه میخواین کلیدی رو چندین بار تکرار کنید میتونید از این الگو استفاده کنید :
SendKeys "{key num}"
که در اینجا key کلیدی است که میخواهید به برنامه بفرستید و num تعداد تکرار آن کلید هست
با تشکر
-
If Like و کاربرد آن
If "Barnamenevis" Like "*name*" Then
Console.Write("Ok")
End If
'Result = Ok
If "Barnamenevis" Like "*evis" Then
Console.Write("Ok")
End If
'Result = Ok
If "Barnamenevis" Like "*Barna*" Then
Console.Write("Ok")
else
Console.Write("Err")
End If
'Result = Err
-
پرینت با استفاده از PrintDocument
این کد از کتاب کوروش مقدسی با یکم دخل و تصرف عملیات پرینت رو انجام میده و نیازی هم به افزودن کنترل به فرم نیست و کافیه فقط کد رو کپی کنید :
PublicClass Form1
Inherits Windows.Forms.Form
FriendWithEvents PrintDocument1 AsNew System.Drawing.Printing.PrintDocument
FriendWithEvents TextBox1 AsNew System.Windows.Forms.TextBox
FriendWithEvents Button1 AsNew Windows.Forms.Button
PrivateSub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
PrintDocument1.Print()
EndSub
PrivateSub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
e.Graphics.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAlias
Dim pfont AsNew Font("Arial", 20)
e.Graphics.DrawString(TextBox1.Text, pfont, Brushes.AliceBlue, 0, 0)
Dim lmargin, Rmargin, Tmargin, Bmargin AsInteger
With PrintDocument1.DefaultPageSettings.Margins
lmargin = .Left
Rmargin = .Right
Tmargin = .Top
Bmargin = .Bottom
EndWith
Dim printWidth, PrintHeight AsInteger
With PrintDocument1.DefaultPageSettings.PaperSize
printWidth = .Width - lmargin - Rmargin
PrintHeight = .Height - Tmargin - Bmargin
EndWith
Dim r As Rectangle
r = New Rectangle(lmargin, Tmargin, printWidth, PrintHeight)
e.Graphics.DrawRectangle(Pens.Black, r)
EndSub
PrivateSub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load
TextBox1.Left = 0
TextBox1.Width = Me.Width
TextBox1.Top = 0
Button1.Top = TextBox1.Top + TextBox1.Height + 10
Button1.Left = 0
Button1.Width = Me.Width
Button1.Text = "پ©یë¢"
Me.Controls.Add(Button1)
Me.Controls.Add(TextBox1)
EndSub
EndClass
-
پرینت فرم
با این کد میتونید یک فرم رو مستقیما به پرینتر بفرستید تو 2008 کار میکنه ولی تو 2005 یا 2003 رو تست نکردم
Public
Class Form1
FriendWithEvents TXTBox1 AsNew TextBox
FriendWithEvents PrintForm1 As Microsoft.VisualBasic.PowerPacks.Printing.PrintFor m
FriendWithEvents BTN AsNew Button
PrivateSub btn_Click(ByVal a AsObject, ByVal b As System.EventArgs) Handles BTN.Click
PrintForm1.Print()
EndSub
PrivateSub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load
Me.PrintForm1 = New Microsoft.VisualBasic.PowerPacks.Printing.PrintFor m(Me.components)
Me.PrintForm1.DocumentName = "document"
Me.PrintForm1.Form = Me
Me.PrintForm1.PrintAction = System.Drawing.Printing.PrintAction.PrintToPrinter
Me.PrintForm1.PrintFileName = Nothing
'Design New Text Box To Form
TXTBox1.Multiline =
True
TXTBox1.Left = 10
TXTBox1.Top = 10
TXTBox1.Height =
Me.Height - 20
TXTBox1.Width = Me.Width - 20
TXTBox1.Text = "This is Sample Code For Test Print Form " & vbCrLf & "Designer : -_- MHM (Ict_Boy_2005@yahoo.com)" & _
vbCrLf & "Publisher WWW.BarnameNevis.ORG"
Me.Controls.Add(TXTBox1)
'Design new Button to form
Me.Height += 100
BTN.Left = 0
BTN.Width = Me.Width
BTN.Top = TXTBox1.Top + TXTBox1.Height
Me.Controls.Add(BTN)
BTN.Height = 100
BTN.Text = "Do Print"
EndSub
EndClass
-
افزودن کنترل در زمان اجرا
https://barnamenevis.org/showpo...2&postcount=47
مثال: یک تکست باکس به فرم اضافه میکند:
کد:
Dim myText As TextBox = New TextBox()
myText.Location = New Point(25, 25)
Me.Controls.Add(myText)
-
یافتن MAC آدرس کارت شبکه
https://barnamenevis.org/showpo...3&postcount=49
ابتدا System.Management رو به References پروژه بیفزایید و سپس :
کد:
Imports System.Management
Private Sub GetMACAddress()
Dim searcher As ManagementObjectSearcher
Dim qry As String = "select * FROM Win32_NetworkAdapter"
searcher = New ManagementObjectSearcher(qry)
For Each wmi_HD As ManagementObject In searcher.Get()
If Not wmi_HD("MacAddress") Is Nothing Then
MessageBox.Show(wmi_HD("MacAddress").ToString())
End If
Next
End Sub
-
نمایش تصاویر در Windows picture and fax viewer از طریق کدنویسی
https://barnamenevis.org/showpo...0&postcount=50
کد:
' //Open with the 'Windows picture and fax viewer':
System.Diagnostics.Process.Start("C:\Windows\syste m32\rundll32.exe ", _
"C:\Windows\system32\shimgvw.dll,ImageView_Fullscr een " + "filename")
اینهم که آسونه اما شاید واسه دوستانی مفید باشه :
کد:
'//Open with the 'Microsoft Paint':
System.Diagnostics.Process.Start("C:\Windows\syste m32\MSPaint.exe ", " filename")
-
وادار کردن لیست باکس به اسکرول تا یک آیتم مشخص
https://barnamenevis.org/showpo...3&postcount=51
مثال - برای آخرین آیتم :
کد:
'// Set the TopIndex property of the ListBox to ensure the
'// most recently added items are visible.
ListBox1.TopIndex = ListBox1.Items.Count - 1
ListBox1.SelectedIndex = ListBox1.Items.Count - 1
-
جابجا کردن فرم با کلیک بر روی هر قسمت از آن - بدون استفاده از توابع API
https://barnamenevis.org/showpo...5&postcount=52
کد:
Private dragging As Boolean
Private pointClicked As Point
Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown
If (e.Button = MouseButtons.Left) Then
'// Turn drag mode on and store the point clicked.
dragging = True
pointClicked = New Point(e.X, e.Y)
Else
dragging = False
End If
End Sub
Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove
If dragging Then
Dim pointMoveTo As Point
'// Find the current mouse position in screen coordinates.
pointMoveTo = Me.PointToScreen(New Point(e.X, e.Y))
'// Compensate for the position the control was clicked.
pointMoveTo.Offset(-pointClicked.X, -pointClicked.Y)
'// Move the form.
Me.Location = pointMoveTo
End If
End Sub
Private Sub Form1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseUp
dragging = False
End Sub
-
انتقال مقادیر خاصیت Text دو تکست باکس از طریق Drag & Drop
کد:
ابتدا خاصیت allow drop را true کنید
Private Sub TextBox1_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles TextBox1.MouseDown
TextBox1.SelectAll()
TextBox1.DoDragDrop(TextBox1.Text, DragDropEffects.Copy)
End Sub
Private Sub TextBox2_DragEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles TextBox2.DragEnter
If (e.Data.GetDataPresent(DataFormats.Text)) Then
e.Effect = DragDropEffects.Copy
Else
e.Effect = DragDropEffects.None
End If
End Sub
Private Sub TextBox2_DragDrop(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles TextBox2.DragDrop
TextBox2.Text = CType(e.Data.GetData(DataFormats.Text), String)
End Sub
-
گرفتن و تسخیر کردن (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