تاپیک جامع نکات در سی شارپ
Arrow روش ارسال ایمیل به چندین گیرنده
کد:
using System.Net.Mail;
کد:
class SendEmail
{
public static void SendMessage(string subject, string messageBody, string fromAddress, string toAddress, string ccAddress)
{
MailMessage message = new MailMessage();
SmtpClient client = new SmtpClient();
message.From = new MailAddress(fromAddress);
// Allow multiple "To" addresses to be separated by a semi-colon
if (toAddress.Trim().Length > 0)
{
foreach (string addr in toAddress.Split(';'))
{
message.To.Add(new MailAddress(addr));
}
}
// Allow multiple "Cc" addresses to be separated by a semi-colon
if (ccAddress.Trim().Length > 0)
{
foreach (string addr in ccAddress.Split(';'))
{
message.CC.Add(new MailAddress(addr));
}
}
message.Subject = subject;
message.Body = messageBody;
client.Host = "YourMailServer";
client.Send(message);
}
}
Arrow فقط یک نمونه از برنامه بتواند اجرا شود (با استفاده از Process)
کد:
using System.Diagnostics;
کد:
static class Program
{
[STAThread]
static void Main()
{
if (IsPrevInstance())
return;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(fals e);
Application.Run(new Form1());
}
private static bool IsPrevInstance()
{
string processName = Process.GetCurrentProcess().ProcessName;
Process[] instances = Process.GetProcessesByName(processName);
if (instances.Length > 1)
return true;
else
return false;
}
}
تعریف یک متغیر بدوت تعیین کردن نوع آن در دات نت فریمورک 3.0 به بعد
کد:
int answer = 42;
string s = "this is a string.";
string[] names = new string[]{"Joe", "Bob", "Sam"};
Arrow دسترسی به بعضی قسمت های ویندوز با shell32
کد:
using Shell32;
اضافه کردن به رفرنس از طریق c:\win....\system32\shell32
کد:
private void Form1_Load(object sender, EventArgs e)
{
listBox2.Items.Add("access.cpl");
listBox2.Items.Add("appwiz.cpl");
listBox2.Items.Add("btcpl.cpl");
listBox2.Items.Add("desk.cpl");
listBox2.Items.Add("directx.cpl");
listBox2.Items.Add("hdwwiz.cpl");
listBox2.Items.Add("inetcpl.cpl");
listBox2.Items.Add("intl.cpl");
listBox2.Items.Add("irprops.cpl");
}
نمونه ای در رویداد یک دکمه
کد:
private void button1_Click(object sender, EventArgs e)
{
objshell.ControlPanelItem(listBox2.SelectedItem.ToString());
}
Arrow جلوگیری از رخ دادن Unhandled Exceptions
در فایل program.cs مربوط به پروژه بعد از دستورات زیر
کد:
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(fals e);
این دستور رو قرار بدین
کد:
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadExce ption);
تشخیص روشن بودن Caps Lock و Num Lock و Scroll Lock بدون API
کد:
IsKeyLocked(Keys.NumLock);
IsKeyLocked(Keys.CapsLock);
IsKeyLocked(Keys.Scroll);
کد:
Console.NumberLock;
Console.CapsLock;
Arrow چک صحیح بودن پسورد از4الی12 در برنامه ویندوز اپلیکشن
کد:
private void txtPass_TextChanged(object sender, EventArgs e)
{
System.Text.RegularExpressions.Regex regex;
regex = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z]\w{3,12}$");
Control ctrl = (Control)sender;
if (regex.IsMatch(ctrl.Text))
{
errorProvider1.SetError(ctrl, "");
}
else
{
errorProvider1.SetError(ctrl, "Not a valid Password.");
}
}
محاسبه تعداد صفحات یک فایل PDF توسط عبارات منظم
کد:
using System.IO;
using System.Text.RegularExpressions;
int PDF_page_counter(string path)
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs);
string pdf_text = sr.ReadToEnd();
//======================================
Regex rgx = new Regex(@"/Type\s*/Page[^s]");
MatchCollection matches = rgx.Matches(pdf_text);
return matches.Count;
}
Arrow متودهای گسترش (Extension Methods)
روشی برای تزریق یک متود تعریف شده به سایر کلاسها بدون دسترسی به سورس و کامپایل مجدد است.
کد:
public static class MyExtensions
{
public static string GetLastCharacter(this System.String str)
{
return str.Substring(str.Length-1, 1);
}
}
Arrow تغییر نام دادن (Rename) یک فایل
کد:
public static void RenameFile(string originalName, string newName)
{
File.Move(originalName, newName);
}
کد:
public static void Rename(FileInfo originalFile, string newName)
{
originalFile.MoveTo(newName);
}
یافتن مقادیر ماکزیمم و مینیمم Primitive Type های عددی
کد:
Int16.MaxValue;
Int16.MinValue;
Int64.MaxValue;
Int64.MinValue;
Double.MaxValue;
Double.MinValue;
Arrow TextBox عددی با اعشار
کد:
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if ( !( char.IsDigit( e.KeyChar) || char.IsControl( e.KeyChar ) ||(e.KeyChar== (char )46)) )
{
e.Handled = true;
}
}
TextBox عددی
کد:
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if ( !( char.IsDigit( e.KeyChar ) || char.IsControl( e.KeyChar ) ) )
{
e.Handled = true;
}
}
Arrow خواندن و نوشتن فایل به صورت unicode با استفاده از richTextBox
کد:
// read text file
richTextBox1.LoadFile(@"C:\Log.txt", RichTextBoxStreamType.UnicodePlainText);
// save text file
richTextBox1.SaveFile(@"C:\Log.txt", RichTextBoxStreamType.UnicodePlainText);
اجرا کردن یک فایل اجرایی با کدنویسی
کد:
System.Diagnostics.Process.Start("mspaint.exe");
Arrow خالی کردن سطل بازیافت ویندوز (ResycleBin)
کد:
using System.Runtime.InteropServices;
کد:
enum RecycleFlags : uint
{
SHERB_NOCONFIRMATION = 0x00000001,
SHERB_NOPROGRESSUI = 0x00000001,
SHERB_NOSOUND = 0x00000004
}
[DllImport("Shell32.dll", CharSet = CharSet.Unicode)]
static extern uint SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath,
RecycleFlags dwFlags);
private void button1_Click(object sender, EventArgs e)
{
uint result = SHEmptyRecycleBin(IntPtr.Zero, null, 0);
}
Arrow کار با کلاس Clipboard و دادن و گرفتن یک رشته متنی به آن
کد:
//clear clipboard
Clipboard.Clear();
//Set Text to clipboard
if (!string.IsNullOrEmpty(textBox1.Text))
Clipboard.SetText(textBox1.Text);
//Get text from clipboard
MessageBox.Show(Clipboard.GetText());
بدست آوردن لیست تمامی درایوها و نوع آنها
کد:
foreach (DriveInfo drv in DriveInfo.GetDrives())
listBox1.Items.Add(drv.Name + ":" + drv.DriveType);
Arrow توابع Params در #C
یک تابع می تواند به تعداد نامحدود پارامتر دریافت کند برای اینکار از دستور Params در تعریف پارامترها استفاده می شود به مثال زیر توجه کنید :
کد:
public static long Sum(params int[] numbers)
{
long Result = 0;
foreach (int number in numbers)
{
Result += number;
}
return Result;
}
Arrow سیاه و سفید کردن عکس با کد نویسی
توسط متد زیر می توانید هر عکسی را به حالت سیاه و سفید در بیارید
کد:
public Image GrayScaleImage(Graphics graph, Image img, int left, int top)
{
ColorMatrix colorMix = new ColorMatrix();
colorMix.Matrix00 = 1 / 3f;
colorMix.Matrix01 = 1 / 3f;
colorMix.Matrix02 = 1 / 3f;
colorMix.Matrix10 = 1 / 3f;
colorMix.Matrix11 = 1 / 3f;
colorMix.Matrix12 = 1 / 3f;
colorMix.Matrix20 = 1 / 3f;
colorMix.Matrix21 = 1 / 3f;
colorMix.Matrix22 = 1 / 3f;
ImageAttributes imgAttrib = 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);
Bitmap bmp = new Bitmap(img);
return bmp;
}
Arrow قرار دادن پروکسی برای ویندوز
کد:
using Microsoft.Win32;
کد:
public static void SetProxy(string Host, string Port)
{
RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microso ft\\Windows\\CurrentVersion\\Internet Settings", true);
registry.SetValue("ProxyEnable", 1);
registry.SetValue("ProxyServer", Host + ":"+ Port);
}
public static void DeleteProxy(string Host, string Port)
{
RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microso ft\\Windows\\CurrentVersion\\Internet Settings", true);
registry.SetValue("ProxyEnable", 0);
registry.DeleteValue("ProxyServer");
}
Arrow مکان نما در تکست باکس
با این کد شما می تونید داخل مکانی (آدرس کرسر تکست باکس ) که با موس در تکست باکس انتخاب کردید تایپ کنید
کد:
int add = textBox7.SelectionStart;
textBox7.Text =textBox7.Text .Insert ( textBox7.SelectionStart , "1");
// = textBox7.SelectionStart + 1;
textBox7.SelectionStart = add+1 ;