مثال - برای آخرین آیتم :
// 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;
Printable View
مثال - برای آخرین آیتم :
// 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;
private bool dragging;
private Point pointClicked;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
// Turn drag mode on and store the point clicked.
dragging = true;
pointClicked = new Point(e.X, e.Y);
}
else
{
dragging = false;
}
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (dragging)
{
Point pointMoveTo;
// Find the current mouse position in screen coordinates.
pointMoveTo = this.PointToScreen(new Point(e.X, e.Y));
// Compensate for the position the control was clicked.
pointMoveTo.Offset(-pointClicked.X, -pointClicked.Y);
// Move the form.
this.Location = pointMoveTo;
}
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
dragging = false;
}
private void textBox_DragDrop(object sender, DragEventArgs e)
{
TextBox txt = (TextBox)sender;
txt.Text = (string)e.Data.GetData(DataFormats.Text);
}
private void textBox_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void textBox_MouseDown(object sender, MouseEventArgs e)
{
TextBox txt = (TextBox)sender;
txt.SelectAll();
txt.DoDragDrop(txt.Text, DragDropEffects.Copy);
}
private void Form1_Load(object sender, EventArgs e)
{
textBox2.DragDrop += new DragEventHandler(this.textBox_DragDrop);
textBox2.MouseDown += new MouseEventHandler(this.textBox_MouseDown);
textBox2.DragEnter += new DragEventHandler(this.textBox_DragEnter);
textBox1.DragDrop += new DragEventHandler(this.textBox_DragDrop);
textBox1.MouseDown += new MouseEventHandler(this.textBox_MouseDown);
textBox1.DragEnter += new DragEventHandler(this.textBox_DragEnter);
textBox1.AllowDrop = textBox2.AllowDrop = true;
}
private void button1_Click(object sender, EventArgs e)
{
this.BackgroundImage= CaptureScreen();
}
private Image CaptureScreen()
{
Bitmap screen = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height);
using (Graphics g = Graphics.FromImage(screen))
{
g.CopyFromScreen(0, 0, 0, 0, screen.Size);
}
return screen;
}
// 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);
و یا :
SystemSounds.Asterisk.Play();
SystemSounds.Hand.Play();
SystemSounds.Exclamation.Play();
SystemSounds.Beep.Play();
SystemSounds.Question.Play();
using System.Media;
private void Form1_Load(object sender, EventArgs e)
{
SoundPlayer player = new SoundPlayer();
string path = "C:\\windows\\media\\ding.wav";
player.SoundLocation = path; //Set the path
player.Play(); //play it
}
منبع : http://www.daniweb.com/code/snippet446.html
using System.Drawing.Printing;
private void GetInstalledPrinters()
{
foreach (string printerName in PrinterSettings.InstalledPrinters)
MessageBox.Show(printerName);
}
// Create a TimeSpan representing 2.5 days.مثال : پیدا کردن اختلاف تعداد روزهای بین دو تاریخ :
TimeSpan timespan1 = new TimeSpan(2, 12, 0, 0);
// Create a TimeSpan representing 4.5 days.
TimeSpan timespan2 = new TimeSpan(4, 12, 0, 0);
// Create a TimeSpan representing 1 week.
TimeSpan oneWeek = timespan1 + timespan2;
// Create a DateTime with the current date and time.
DateTime now = DateTime.Now;
// Create a DateTime representing 1 week ago.
DateTime past = now - oneWeek;
// Create a DateTime representing 1 week in the future.
DateTime future = now + oneWeek;
DateTime dateFrom = DateTime.Parse("10/10/2007");و یا :
DateTime dateTo = DateTime.Parse("11/12/2007");
TimeSpan ts = dateTo - dateFrom;
int days = ts.Days;
DateTime dtFirst = new DateTime(2007, 10, 10);
DateTime dtSecond = new DateTime(2007, 11, 12);
TimeSpan diffResult = dtSecond.Subtract(dtFirst);
using System.IO;
مخفی و فقط خواندنی کردن یک فایل :
FileInfo file = new FileInfo(@"C:\test.txt");
file.Attributes = file.Attributes | FileAttributes.ReadOnly | FileAttributes.Hidden;
تغییر خاصیت (حذف حالت فقط خواندنی مثال قبل):
file.Attributes = file.Attributes & ~FileAttributes.ReadOnly;
using System.IO;
public long CalculateDirectorySize(DirectoryInfo directory, bool includeSubdirectories)
{
long totalSize = 0;
// Examine all contained files.
FileInfo[] files = directory.GetFiles();
foreach (FileInfo file in files)
{
totalSize += file.Length;
}
// Examine all contained directories.
if (includeSubdirectories)
{
DirectoryInfo[] dirs = directory.GetDirectories();
foreach (DirectoryInfo dir in dirs)
{
totalSize += CalculateDirectorySize(dir, true);
}
}
return totalSize;
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(CalculateDirectorySize(new DirectoryInfo( @"C:\WINDOWS\System32"), true).ToString());
}
using System.IO;
private void CreateTextFile()
{
using (FileStream fs = new FileStream("C:\\test.txt", FileMode.Create))
{
using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
{
w.WriteLine(124.23M);
w.WriteLine("Salaam!");
w.WriteLine('!');
}
}
}
private string ReadFromTextFile()
{
StringBuilder sb = new StringBuilder();
using (FileStream fs = new FileStream("C:\\test.txt", FileMode.Open))
{
using (StreamReader r = new StreamReader(fs, Encoding.UTF8))
{
sb.AppendLine(r.ReadLine());
sb.AppendLine(r.ReadLine());
sb.AppendLine(r.ReadLine());
}
}
return sb.ToString();
}
string filename = @"..\..\myfile.txt";
string fullPath = @"c:\Temp";
string filename = Path.GetFileName(filename);
string fullPath = Path.Combine(fullPath, filename);
// (fullPath is now "c:\Temp\myfile.txt")
string randomFileName = System.IO.Path.GetRandomFileName();
و برای ایجاد نام منحصر بفرد برای فایلهای موقت :
string tfile = Path.GetTempFileName();
System.Diagnostics.Process.Start("iexplore.exe", "www.barnamenevis.org");
و برای مثال در فایرفاکس :
System.Diagnostics.Process.Start("C:\Program Files\Mozilla Firefox\FireFox.exe", "www.barnamenevis.org");
public enum Days { Sat = 1, Sun, Mon, Tue, Wed, Thu, Fri };
int x = (int) Days.Mon;
public enum Days { Sat = 1, Sun, Mon, Tue, Wed, Thu, Fri };
System.Type t = typeof(Days);
foreach (string s in Enum.GetNames(t))
{
listBox1.Items.Add(s);
}
عادت کردن به میانبرها میتواند سرعت کدنویسی شما را افزایش دهد :
نقل قول:
- CTRL+ALT+L: View Solution Explorer. I use Auto Hide for all of my tool windows to maximize screen real estate. Whenever I need to open the Solution Explorer, it’s just a shortcut away. Related shortcuts: CTRL+ALT+X (Toolbox), F4 (Properties), CTRL+ALT+O (Output), CTRL+\, E (Error List), CTRL+\, T (Task List).
- F12: Go to definition of a variable, object, or function.
- SHIFT+F12: Find all references of a function or variable.
- F7: Toggle between Designer and Source views.
- CTRL+PgDn: Toggle between Design and Source View in HTML editor.
- F10: Debug - step over. Related debugging shortcuts: F11 (debug - step into), SHIFT-F11 (debug - step out), CTRL-F10 (debug - run to cursor). F9 (toggle breakpoint).
- CTRL+D or CTRL+/: Find combo (see section on Find Combo below).
- CTRL+M, O: Collapse to Definitions. This is usually the first thing I do when opening up a new class.
- CTRL+K, CTRL+C: Comment block. CTRL+K, CTRL-U (uncomment selected block).
- CTRL+-: Go back to the previous location in the navigation history.
- ALT+B, B: Build Solution. Related shortcuts: ALT+B, U (build selected Project), ALT+B, R (rebuild Solution).
- CTRL+ALT+Down Arrow: Show dropdown of currently open files. Type the first few letters of the file you want to select.
- CTRL+K, CTRL+D: Format code.
- CTRL+L: Delete entire line.
- CTRL+G: Go to line number. This is useful when you are looking at an exception stack trace and want to go to the offending line number.
- SHIFT+ALT+Enter: Toggle full screen mode. This is especially useful if you have a small monitor. Since I upgraded to dual 17" monitors, I no longer needed to use full screen mode.
- CTRL+K, X: Insert "surrounds with" code snippet. See Snippets tip below.
- CTRL+B, T: Toggle bookmark. Related: CTRL+B, N (next bookmark), CTRL+B, P (prev bookmark).
منبع : http://www.chinhdo.com/20070920/top-11-visual-studio-2005-ide-tips-and-tricks-to-make-you-a-more-productive-developer/
مثال : تغییر رنگ پشت زمینه ی تمامی فرمهای باز در یک برنامه :
foreach (Form frm in Application.OpenForms)
frm.BackColor = Color.Fuchsia;
private void button1_Click(object sender, EventArgs e)
{
Application.Restart();
}
برنامه تمامی message های درون message queue فعلی (از قبیل رخدادها و ...) را پردازش میکند.
Application.DoEvents();یک مثال ساده :
محو شدن تدریجی یک فرم با تغییر دادن خاصیت Opacity
using System.Diagnostics;این تغییرات را در کلاس مربوط به StartUp برنامه اعمال کنید :
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;
}
}
به جای نوشتن :
private string userName;میتوانید بنویسید :
public string UserName
{
get { return userName; }
set { userName = value; }
}
public string UserName { get; set; }پیشنهاد خود مایکروسافت هم استفاده از حالت دوم است چون اگر snippet مربوط به prop رو اجرا کنید میبینید که برای این حالت تغییر یافته است.
چند نکته :
1- در پشت پرده و بصورت اتوماتیک ساختاری همانند پراپرتیهای سنتی تشکیل میشود اما دسترسی به فیلد آن امکان پذیر نیست.
2- اگر بخواهید یک پراپرتی فقط خواندنی یا فقط نوشتنی ایجاد کنید باید از همان روش سنتی استفاده کنید.
3- این نوع پراپرتی فقط جهت encapsualte کردن یک فیلد به کار میره و چنانچه نیاز به نوشتن عملیات خاصی (مثل اعتبارسنجی و ...) داشته باشید؛ باید از همان نوع سنتی استفاده کنید.
فرض کنید کلاسی برای کاربران خود به این شکل تعریف کردید :
public class Userحال در برنامه میتوانید به اشکال زیر آبجکت آن را مقدار دهی کنید :
{
public string Password { get; set; }
public string UserName { get; set; }
public DateTime LastLogon { get; set; }
}
User u1 = new User { UserName="sinpin", Password="123", LastLogon=DateTime.Now };
User u2 = new User { UserName = "sinpin", Password = "123" };
User u3 = new User { UserName = "sinpin" };
به همین منوال میتوانید برای هر کلاسی استفاده کنید. مثلا ساخت یک نمونه از Form2 با تغییر برخی مشخصات :
new Form2 { Text = "Test", BackColor = Color.Red }.Show();
new Form2 { StartPosition = FormStartPosition.CenterScreen }.Show();
Implicit typed local variables
با استفاده از کلمه کلیدی var :
برای مثال نوشتن :
var answer = 42;معادل است با :
var s = "this is a string.";
var names = new string[]{"Joe", "Bob", "Sam"};
int answer = 42;پس از مقداردهی نوع متغیر مشخص خواهد شد.
string s = "this is a string.";
string[] names = new string[]{"Joe", "Bob", "Sam"};
اینها درست هستند :
var a = "See", b = "Spot", c = "run";اما اینها اشتباه هستند :
string[] names = new string[]{"Jim", "Joe", "Bob"};
var b = new[] {1, 2.0, 3.5, 4.75}; // double[]
var a = new[] {1, 2, 3, 4, 5}; // int[]
foreach (var name in names)
{
...
}
var x = null;چند نکته :
var a = 22, b = "Spot", c = 9.5;
var c = new[] {1, "Name", 2, "Address");
- بلافاصله بعد از تعریف، متغیر باید مقداردهی شود در غیر اینصورت خطای زمان کامپایل رخ میدهد.
- عمل تعیین نوع تنها یکبار انجام شده و پس از آن قابل تغییر نیست.
مثال 1 -
فرض کنیم کلاسی مانند زیر تعریف کردیم :
public class Userحال در فرم خود بنویسید :
{
public int Age { get; set; }
public string UserName { get; set; }
}
User[] users = new User[] {
new User{UserName="Ahmad", Age=20},
new User{UserName="Maryam", Age=17},
new User{UserName="Ali", Age=29},
new User{UserName="Hooman", Age=33},
new User{UserName="Sara", Age=22},
};
var mySelect = from user in users where user.Age > 20 && user.Age < 30 select user.UserName;
foreach (string uname in mySelect)
MessageBox.Show(uname);
مثال 2 -
List<string> words = new List<string> {
"Word1", "World", "Word2", "Word3", "World4" };
var wordQuery = from word in words where word == "World" select new { word };
foreach (var name in wordQuery)
MessageBox.Show( "-> Hello " + name.word);
میتونید کالکشنها رو در همان زمان تعریف مقداردهی نیز کنید.
مثال 1-
List<string> names = new List<string> {"Jim", "Joe", "Bob", "Sam"};مثال 2- با فرض داشتن کلاسی مانند:
public class Personمیتونیم بنویسیم :
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
List<Person> people = new List<Person> {
new Person { FirstName = "Scott", LastName = "Guthrie", Age = 32 },
new Person { FirstName = "Bill", LastName = "Gates", Age = 50 },
new Person { FirstName = "Susanne", LastName = "Guthrie", Age = 32 }
};
روشی برای تزریق یک متود تعریف شده به سایر کلاسها بدون دسترسی به سورس و کامپایل مجدد است.
(البته این تزریق بصورت موقت و ظاهری است و در پشت پرده از طریق یک متود استاتیک اینکار انجام میشود.)
مثال - میخواهیم متودی به کلاس string بیافزاییم که آخرین حرف یک رشته را برگرداند. یک کلاس استاتیک به شکل زیر تعریف میکنیم : (توجه : اسم کلاس اهمیتی ندارد)
public static class MyExtensionsحال میتونیم این متد را در لیست متدهای یک string - مانند زیر - مشاهده کنیم :
{
public static string GetLastCharacter(this System.String str)
{
return str.Substring(str.Length-1, 1);
}
}
string temp = "Sinpin";
MessageBox.Show( temp.GetLastCharacter());
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);
}
}
منبع : http://code.msdn.microsoft.com/sendemail
نمونه برنامه را می توانید در اخر همین پست دانلود کنید
برای این عمل به یک رویداد (MouseMove) برای pictureBox منبع نیاز دارید و دو رویداد (DragDrop) و ( DragEnter) از pictureBox مقصد. که نحوه کد کردن آن ها به شکل زیر است
private void picBoxSource_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left & picBoxSource.Image != null)
{
picBoxSource.DoDragDrop(picBoxSource.Image, DragDropEffects.All);
}
}
private void picBoxDest_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Bitmap))
{
e.Effect = DragDropEffects.Copy;
}
else
e.Effect = DragDropEffects.None;
}
private void picBoxDest_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Bitmap))
{
picBoxDest.Image = (Image)e.Data.GetData(DataFormats.Bitmap);
}
}
نکته : خاصیت AllowDrop مربوط به pictureBox مقصد را بایستی true کنید. دقت داشته باشید که این خاصیت، در پنجره خواص مربوط به pictureBox وجود نداره و باید اونو از طریق کد نویسی اعمال کنید.
موفق باشید
مهدی کیانی
< نمونه برنامه را از آخر همین پست دریافت کنید >
شما می توانید ، یک فرم About ("در باره برنامه" .. یا بعضا "در برباره ما ")، به پروژه خود اضافه کنید. بدون اینکه کد نویسی برای قسمت های مختلف آن انجام بدین.
برای این کار روی نام سولوشن برنامه کلیک راست کنید، و از گزینه properties ،تب مربوط به Application را انتخاب کنید. (Default Tab)
سپس روی گزینه Assembly Information کلیک کنید تا پنجره مربوط به Assembly Information باز شود.
مانند شکل زیر
پس از پر کردن فیلد ها با اطلاعات دلخواه شما، از منوی project و از گزینه Add New Item یک AboutBox به فرم خود اضافخ کنید. (به عنوان نمونه ABoutBox1)
حال در هر کجا که می خواهید، کافی است کد زیر را بنویسید، تا فرم About نمایش داده شود.
new AboutBox1().ShowDialog(this);
مانند شکل زیر
موفق باشید
مهدی کیانی
< نمونه برنامه را می تونین در آخر مطالب دریافت کنید>
توسط متد زیر می توانید هر عکسی را به حالت سیاه و سفید یا همون grayScale در بیارین
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;
}
عملکر متد خیلی واضحه.
کلا با ImageAttribute ها و ColorMiser ها خیلی کارهای خوشکلی میشه کرد که به مرور میذارم اینجا
راستی این کد به درد اون دسته عزیزانی که می خواستن، shutdown ویندوز را شبیه سازی کنند خیلی خوبه. (اینکه می خواستن از دسکتاپ عکس بگیرن و بعد اونو تار کنن) البته برای تار کردن عکس ها، راه های دیگه ای هم هست که انشالا به مرور
نمونه
در حاشیه :
تورو خدا می بینین؟ فردا ظهر امتحان ارشد دارم، الان ساعت 1:30 نصف شبه :قهقهه: نشستم برای شما و فقط به عشق شما دوستان مطلب می نویسم
موفق باشید
یا علی مدد
مهدی کیانی
این کلاس مختص دات نت 3.5 (به بعد) است و جهت استفاده باید System.Core رو نیز به References پروژه ی خود بیافزایید.
مثال - بدست آوردن تاریخ و زمان فعلی در توکیو :
TimeZoneInfo tzSource = TimeZoneInfo.Local;
TimeZoneInfo tzDestination = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
string sourceTime = TimeZoneInfo.ConvertTime(DateTime.Now,
tzSource, tzDestination).ToShortTimeString();
MessageBox.Show(sourceTime);
این روش مختص دات نت 3.5 (به بعد) است.
using System.Collections.ObjectModel;بدست آوردن Id و DisplayName نواحی :
ReadOnlyCollection<TimeZoneInfo> zones = TimeZoneInfo.GetSystemTimeZones();
foreach (TimeZoneInfo zone in zones)
{
listBox1.Items.Add(zone.Id);
listBox2.Items.Add(zone.DisplayName);
}
using System.IO;
//To create a directoryمنبع : http://www.eggheadcafe.com/community...in-folder.aspx
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
FileInfo FI = new FileInfo(@"C:\MyFile.Txt");
Console.WriteLine("File size of MyFile.Txt: {0}", FI.Length);
//copy example
String DateTemp = DateTime.Now;
File.Copy(@"P:\PRD\Products\AHM\prod.CD\Database\d ata.mdb",
@"P:\PRD\Products\AHM\prod.CD\Database\"+ DateTemp +"-data.mdb");
معنای کلمات متداولی که معمولا دات نت کار ها خواهند شنید. مخصو.صا تازه کار های عزیز
1 ) CLR
مخفف : Common Language RunTime
معنا :
محیط زمان اجرای برنامه های دات نت
-------------------------------------------------------------------------
2) CTS
مخفف : Common Type System
معنا : تایپ هایی هستند که در همه زبان های دات نت شناخته شده هستند و معمولا یک نام مستعار در هر زبان مجزا دارند.
مثلا System.Int32 در زبان C# همان int و در زبان VB همان Integer است.
نکته:
CTS تایپ ها برای همانهنگ سازی بین زبان های مختلف دات نتی استفاده میشه
----------------------------------------------------------------------------------------------
3) IL
مخفف : Intermediate Language
معنا : زبان واسطی که در مرحله اول کامپیا برنامه ها، تمامی کد های نوشته شده با زبان های دات نت (اعم از سی شارپ، وی بی و ..) به این زبان ترجمه می شوند. (باز هم جهت سازگاری بین زبان های مختلف در دات نت)
مثال
تکه کدی به زبان C#
public int add(int num1, int num2)
{
return num1 + num2;
}
همان تکه کد به زبان VB
Public Function add(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
Return num1 + num2
End Function
تکه کد فوق به زبان IL
.method public hidebysig instance int32 add(int32 num1, int32 num2) cil managed
{
.maxstack 2
.locals init (
[0] int32 CS$1$0000)
L_0000: nop
L_0001: ldarg.1
L_0002: ldarg.2
L_0003: add
L_0004: stloc.0
L_0005: br.s L_0007
L_0007: ldloc.0
L_0008: ret
}
نکته : شما می توانید کل برنامه خود را به زبان IL بنویسید و سپس آن را اجرا کنید. ولی اصولا هیچ آدم عاقلی این کار را نمیکنه :لبخند:
------------------------------------------------------------------------------------------
4 ) CIL
مخفف : Common Intermediate Langiage
معنا : معالد همون IL هست.
نکته: استفاده از IL متداول تر است.
-----------------------------------------------------------------------------------------
5) VES
مخفف : Virtual Executation Systeme
معنا : معادل CLR هست
نکته: CLR متداول تر است.
---------------------------------------------------------------------------------
6) CLI
مخفف : Common Language Interface
معنا : به مجموعه CLR و CTS و CLI می گویند
فعلا همینا تو ذهنم بود
اگه بازم یادم اومد، همین جا میذارم
موفق باشید
using System.IO;فایلها را در مسیرC:\CopiedFolder کپی میکند :
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.Description = "Find Folder to Copy.";
if (fbd.ShowDialog() == DialogResult.OK)
{
string[] files = Directory.GetFiles(fbd.SelectedPath);
Directory.CreateDirectory(@"C:\CopiedFolder");
for (int i = 0; i < files.Length; i++)
{
string tmpFileExt = Path.GetExtension(files[i]);
string tmpFileName = Path.GetFileNameWithoutExtension(files[i]);
File.Copy(files[i], @"C:\CopiedFolder\" + tmpFileName + tmpFileExt, true);
}
}
منبع : http://www.se7ensins.com/forums/c/84...g-folders.html
نسل جدید ساخت UI است که با پیدایش دات نت فریمورک 3.0 بوجود آمد.
با استفاده از زبان XAML باعث تفکیک و جدایی ظاهر یک فرم و منطق پشت زمینه ی آن میشود، لذا برنامه نویس و گرافیست میتوانند در کنار یکدیگر به راحتی روی یک برنامه کار کنند.
قبلا برای ساخت یک برنامه که قابلیتهایی مانند :
Graphical interface, On-screen documents, Fixed-format documents, Video and audio, 2D/3D graphics, Image Processing داشته باشد؛ میبایستا کتابخانه های مختلفی مانند :
DirectX, +GDI, PDF, Media Player, Windows Form, ... را میشناختید و با آنها کار میکردید؛ در حالیکه هم اکنون تنها با استفاده از WPF تمامی آن قابلیتها در دسترس هستند.
پیشنهاد میکنم حتما لینک بسیار مفید زیر رو ببینید :
http://msdn2.microsoft.com/en-us/library/aa970268.aspx
این هم خوبه :
http://en.wikipedia.org/wiki/Windows...ion_Foundation
using System.IO;void CopyDirectory(DirectoryInfo source, DirectoryInfo destination)منبع - کتاب : Visual C# 2005 Recipes: A Problem-Solution Approach
{
if (!destination.Exists)
destination.Create();
// Copy all files.
FileInfo[] files = source.GetFiles();
foreach (FileInfo file in files)
file.CopyTo(Path.Combine(destination.FullName, file.Name));
// Process subdirectories.
DirectoryInfo[] dirs = source.GetDirectories();
foreach (DirectoryInfo dir in dirs)
{
// Get destination directory.
string destinationDir = Path.Combine(destination.FullName,dir.Name);
// Call CopyDirectory() recursively.
CopyDirectory(dir, new DirectoryInfo(destinationDir));
}
}
Serialize :
فرآیندی برای تبدیل یک آبجکت و یا گرافی متشکل از چند آبجکت به یک حالت خطی (و جریان وار) از بایت ها برای انتقال و یا ذخیره سازی در محلی دیگر است.
Deserialize :
عمل برعکس سریالیزشین است؛ یعنی دوباره ساختن آبجکت از روی جریانی از بایتها .
انواع فرمت ها در سریالیزشین :
1- Binary : بصورت باینری سریالایز میکند. (فشرده ترین و efficient ترین حالت است)
SOAP -2 : بصورت soap سریالایز میکند. (برای ارسال در شبکه و جایی که از تحت دات نت بودن کلاینتها مطمئن نیستیم)
XML -3 : بصورت xml سریالایز میکند. (برای ارسال تحت شبکه - مزیت : خوانایی)
برخی از موارد کاربرد سریالزیشین:
1- کپی یک انشعاب از آبجکتها
2- انتقال اطلاعات در شبکه
3- نگهداری state ها و snapshot های مختلف در یک برنامه (برای موارد حساس : مثل تراکنشهای بانکی و ...)
4- پیاده سازی Deep Copy و Shallow Copy
فرض کنیم که :
int a = 3, b = 5;
حال میتونیم به جای نوشتن :
string result = a.ToString() + "+" + b.ToString() + "=" + (a + b).ToString();
بسادگی بنویسیم :
string result = string.Format("{0}+{1}={2}", a, b, a + b);
استفاده از Place Holder ها (حالت دوم) ضمن خوانایی بیشتر برنامه، معمولا کدنویسی کمتری نیز طلب میکند.
using System.Drawing;منبع : http://www.devtopics.com/c-getpixel-and-setpixel/
using System.Runtime.InteropServices;
using System.Windows.Forms;
[DllImport( "user32.dll" )]
static extern IntPtr GetDC( IntPtr hWnd );
[DllImport( "user32.dll" )]
static extern int ReleaseDC( IntPtr hWnd, IntPtr hDC );
[DllImport( "gdi32.dll" )]
static extern int GetPixel( IntPtr hDC, int x, int y );
[DllImport( "gdi32.dll" )]
static extern int SetPixel( IntPtr hDC, int x, int y, int color );
static public Color GetPixel( Control control, int x, int y )
{
Color color = Color.Empty;
if (control != null)
{
IntPtr hDC = GetDC( control.Handle );
int colorRef = GetPixel( hDC, x, y );
color = Color.FromArgb(
(int)(colorRef & 0x000000FF),
(int)(colorRef & 0x0000FF00) >> 8,
(int)(colorRef & 0x00FF0000) >> 16 );
ReleaseDC( control.Handle, hDC );
}
return color;
}
static public void SetPixel( Control control, int x, int y, Color color )
{
if (control != null)
{
IntPtr hDC = GetDC( control.Handle );
int argb = color.ToArgb();
int colorRef =
(int)((argb & 0x00FF0000) >> 16) |
(int)(argb & 0x0000FF00) |
(int)((argb & 0x000000FF) << 16);
SetPixel( hDC, x, y, colorRef );
ReleaseDC( control.Handle, hDC );
}
}
using System.Drawing.Imaging;Bitmap bmp = new Bitmap(picturebox1.Image);
//read
Color c = bmp.GetPixel(1, 1);
//write
bmp.SetPixel(2, 2, c);
مثال - بنقل از : http://msdn2.microsoft.com/en-us/lib....getpixel.aspx
private void GetPixel_Example(PaintEventArgs e)
{
// Create a Bitmap object from an image file.
Bitmap myBitmap = new Bitmap("Grapes.jpg");
// Get the color of a pixel within myBitmap.
Color pixelColor = myBitmap.GetPixel(50, 50);
// Fill a rectangle with pixelColor.
SolidBrush pixelBrush = new SolidBrush(pixelColor);
e.Graphics.FillRectangle(pixelBrush, 0, 0, 100, 100);
}
using Microsoft.Win32;// Create SubKey
Registry.LocalMachine.CreateSubKey(@"Software\Sinp in", RegistryKeyPermissionCheck.ReadWriteSubTree);
//Create Key and Set Value
RegistryKey reg = 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\Sinp in");
// Read Key Value
string val = reg.GetValue("QWord").ToString();
// Retrieve All Keys
foreach (string s in reg.GetValueNames())
MessageBox.Show(s);
using System.Drawing.Drawing2D;private static Image resizeImage(Image imgToResize, Size size)
{
int sourceWidth = imgToResize.Width;
int sourceHeight = imgToResize.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)size.Width / (float)sourceWidth);
nPercentH = ((float)size.Height / (float)sourceHeight);
if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap b = new Bitmap(destWidth, destHeight);
Graphics g = Graphics.FromImage((Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
g.Dispose();
return (Image)b;
}
منبع : http://blog.paranoidferret.com/?p=11
private static Image cropImage(Image img, Rectangle cropArea)
{
Bitmap bmpImage = new Bitmap(img);
Bitmap bmpCrop = bmpImage.Clone(cropArea,
bmpImage.PixelFormat);
return (Image)(bmpCrop);
}
مثال از نحوه ی استفاده :
private void button1_Click(object sender, EventArgs e)
{
pictureBox2.Image = cropImage(pictureBox1.Image, new Rectangle(10,10,100,100));
}
منبع : http://blog.paranoidferret.com/?p=11
using System.Drawing.Imaging;public static Bitmap MakeGrayscale(Bitmap original)منبع : http://blog.paranoidferret.com/index...-to-greyscale/
{
//create a blank bitmap the same size as original
Bitmap newBitmap =
new Bitmap(original.Width, original.Height);
//get a graphics object from the new image
Graphics g = Graphics.FromImage(newBitmap);
//create the grayscale ColorMatrix
ColorMatrix colorMatrix = new ColorMatrix(
new float[][]{
new float[] {.3f, .3f, .3f, 0, 0},
new float[] {.59f, .59f, .59f, 0, 0},
new float[] {.11f, .11f, .11f, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}});
//create some image attributes
ImageAttributes attributes = 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;
}
مثال -
private void button1_Click(object sender, EventArgs e)
{
Bitmap b = (Bitmap) pictureBox1.Image;
pictureBox2.Image = MakeGrayscale(b);
}
public T NumToEnum<T>(int number)
{
return (T)Enum.ToObject(typeof(T), number);
}
مثال - با فرض داشتن :
public enum DaysOfWeek
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
میتوانیم بنویسیم :
int day = 3;
DaysOfWeek d = NumToEnum<DaysOfWeek>(day);
//d is now DaysOfWeek.Thursday
منبع : http://blog.paranoidferret.com/index...from-a-number/
public static T StringToEnum<T>(string name)
{
return (T)Enum.Parse(typeof(T), name);
}
مثال - با فرض داشتن :
public enum DaysOfWeek
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
میتوانیم بنویسیم :
DaysOfWeek d = StringToEnum<DaysOfWeek>("Monday");
//d is now DaysOfWeek.Monday if(Enum.IsDefined(typeof(DaysOfWeek), "Katillsday"))
StringToEnum<DaysOfWeek>("Katillsday");
منبع : http://blog.paranoidferret.com/index...from-a-string/
class GenericSingleton<T> where T : class, new()
{
private static T instance;
public static T GetInstance()
{
lock (typeof(T))
{
if (instance == null)
{
instance = new T();
}
return instance;
}
}
}
مثال از نحوه ی استفاده :
AutoFactory autoF = GenericSingleton<AutoFactory>.GetInstance();
منبع : http://blog.paranoidferret.com/index...leton-pattern/
private Bitmap rotateImage(Bitmap b, float angle)
{
//create a new empty bitmap to hold rotated image
Bitmap returnBitmap = new Bitmap(b.Width, b.Height);
//make a graphics object from the empty bitmap
Graphics g = Graphics.FromImage(returnBitmap);
//move rotation point to center of image
g.TranslateTransform((float)b.Width / 2, (float)b.Height / 2);
//rotate
g.RotateTransform(angle);
//move image back
g.TranslateTransform(-(float)b.Width / 2, -(float)b.Height / 2);
//draw passed in image onto graphics object
g.DrawImage(b, new Point(0, 0));
return returnBitmap;
}
مثال استفاده :
private void button1_Click(object sender, EventArgs e)
{
Bitmap b = (Bitmap) pictureBox1.Image;
pictureBox2.Image = rotateImage(b, 60);
}
منبع : http://blog.paranoidferret.com/index...diting-rotate/