-
آیا کاربر جاری Administrator هست؟
برای اینکه متوجه بشین که آیا کاربر جاری تون عضوی از گروه کاربران Administrator هست یا نه از این کد استفاده کنین:
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
string role = "BUILTIN\\Administrators";
bool IsAdmin = principal.IsInRole(role));
-
1 ضمیمه
قرار دادن یک کنترل داخل منو
حتمالا دیدید که توی بعضی نرم افزار ها داخل یک منو آیتم یک کنترل وجود داره. مثلا یه منو که توی اون یک ComboBox نشون داده می شود. یا هر کنترل دیگری شبیه به اون.
برای اینکار یه کلاسی وجود داره به نام ToolStripControlHost
شما می تونین با ساختن یک object از این کلاس و پاس کردن کنترل مورد نظر در Constructor اون و در نهایت اضافه کردن اون به مثلا Menu یا ContextMenu و یا Toolbar از اون استفاده کنین.
کد:
private void Form1_Load(object sender, EventArgs e)
{
MonthCalendar picker = new MonthCalendar();
picker.DateSelected += new DateRangeEventHandler(picker_DateSelected);
ToolStripControlHost host = new ToolStripControlHost(picker);
fileToolStripMenuItem.DropDownItems.Insert(2,host) ;
}
void picker_DateSelected(object sender, DateRangeEventArgs e)
{
MonthCalendar picker = ((MonthCalendar)sender);
this.Text = picker.SelectionStart.ToString("yyyy/MMM/dd");
}
نتیجه این کد بالا این تصویر می شود.
این سوال MCTS Windows 70-526 بود.
-
1 ضمیمه
یک مثال ساده از پیاده سازی delegate
فرض کنید متود ساده زیر را داریم و میخواهیم به عنوان پارامتر به متود دیگری ارسال کنیم
public void DisplayNumber(int num)
{
MessageBox.Show(string.Format("The value is {0}", num));
}
ابتدا نوع داده ای جدیدی ازdelegate با همین signature یعنی از نوع void و با پارامتر ی از نوع int تعریف می کنیم:
public delegate void ProcessNumber(int number);
سپس متغیری از نوع داده ا ی delegate تعریف شده به صورت زیر اعلان میکنیم :
ProcessNumber pn = new ProcessNumber(DisplayNumber);
حال میتوان این متغیر را به عنوان پارامتر به هر متود دلخواهی صادر کرد (مثلا متود زیر):
public int MultiplyNumbers(int a, int b, ProcessNumber pn)
{
int op = a * b;
pn(op);
return op;
}
با این فراخوانی :
MultiplyNumbers(4, 5, pn);
منبع:سری های آموزشی TestOut C# for programmers
http://www.testout.com
-
بدست آوردن خروجی دستورهای خط فرمان
using System.Diagnostics;
private static string CaptureCommandPromptOutput(string command, string argument)
{
ProcessStartInfo info = new ProcessStartInfo(command, argument);
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
info.CreateNoWindow = true;
Process p = new Process();
p.StartInfo = info;
p.Start();
return p.StandardOutput.ReadToEnd();
}
مثال از نحوه استفاده :
richTextBox1.Text = CaptureCommandPromptOutput("cmd", "/c dir");
و یا :
richTextBox1.Text = CaptureCommandPromptOutput("Ping", "127.0.0.1");
-
Map کردن درایوهای شبکه به کمک اجرای دستورات خط فرمان
using System.Diagnostics;
Process.Start("NET", @"USE U: \\127.0.0.1\Sinpin /PERSISTENT:YES");
-
به دست آوردن تعداد خطوط متن در یک textBox
API مربوطه
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
const uint EM_GETLINECOUNT = 0xBA;
IntPtr wp=IntPtr.Zero;
IntPtr lp=IntPtr.Zero;
طریقه استفاده
IntPtr lines = SendMessage(textBox1.Handle, EM_GETLINECOUNT,wp,lp);
MessageBox.Show(lines.ToInt32().ToString());
نمونه برنامه
-
معرفی لینک دانلود چند فیلم آموزشی ساده در مورد...
1
Video How to: Creating a Simple Data Application
video summary
نقل قول:
Displaying data from a database on a Windows Form is easy with Visual Studio 2008. You can display data on forms in Windows applications by dragging items from the Data Sources window onto your form.
This video shows how to create an application that displays data from two related tables in a database. The following tasks are included in the process:
How to create a Windows-based application.
How to create and configure a dataset that is based on the Customers and Orders tables in the Northwind database by using the Data Source Configuration Wizard.
How to add controls to display data from the Customers table.
How to test the application, selecting different customers and verifying that the correct orders are shown for the selected customer.
How to modify data and save it back to the database.
watch the video
download the video
------------------------------------------------------------
2)
Creating an N-Tier Data Application
-------------------------------------------------------------
3)
Writing Queries in C# (LINQ)
-----------------------------------------------------------
4)
Create a C# WPF Application
--------------------------------------------------
اطلاعات مربوط به ویدئو های 2 تا 4 را با کلیک کردن بر روی آن ها می تونید مشاهده کنید.
-
انجام عملیات متداول بر رشته ها
حذف تمامی whiteSpace ها :
//STRIPS WHITE SPACES FROM BOTH START + FINSIHE
string Name = " String Manipulation " ;
string NewName = Name.Trim();
حذف whiteSpace ها (یا حروفی خاص) از آخر رشته :
//STRIPS CHRS FROM THE END OF THE STRING
string Name = " String Manipulation " ;
//SET OUT CHRS TO STRIP FROM END
char[] MyChar = {' ','n'};
string NewName = Name.TrimEnd(MyChar);
حذف whiteSpace ها (یا حروفی خاص) از ابتدای رشته :
//STRIPS CHRS FROM THE START OF THE STRING
string Name = " String Manipulation " ;
//SET OUT CHRS TO STRIP FROM END
char[] MyChar = {' ','S'};
string NewName = Name.TrimStart(MyChar);
جستجوی یک رشته ی در رشته ی دیگر :
string MainString = "String Manipulation";
string SearchString = "pul";
int FirstChr = MainString.IndexOf(SearchString);
جایگزین کردن بخشی از یک رشته :
string MainString "String Manipulatin";
string CorrectString = MainString.Replace("Manipulatin", "Manipulation");
حذف کردن بخشی از یک رشته :
string MainString = "S1111tring Manipulation";
string NewString = MainString.Remove(1,4);
تفکیک یک رشته :
string MainString = "String Manipulation";
string [] Split = MainString.Split(new Char [] {' '});
//SHOW RESULT
MessageBox.Show(Convert.ToString(Split[0]));
MessageBox.Show(Convert.ToString(Split[1]));
منبع : http://www.developerfusion.co.uk/show/4398/
-
مقایسه دو رشته بدون توجه به بزرگی و کوچکی حروف
if (string.Compare(str1, str2, false) == 0) // Case Insensitive!
Console.WriteLine("Two strings are similar to each other.");
مقایسه دو رشته با توجه به بزرگی و کوچکی حروف
if (string.Compare(str1, str2, true) == 0) // Case Insensitive!
Console.WriteLine("Two strings are similar to each other.");
برگرداندن یک رشته ار داخل یک رشته
string MainString = "String Manipulation";
//SHOW RESULT
MessageBox.Show(str1.Substring(6, 12));
روش دیگر استفاده از تابع Split
string[] aryStrings;
str1 = "Hello,How;Are,You";
aryStrings = str1.Split(',', ';', '*');
foreach (string str in aryStrings)
MessageBox.Show("{0}", str);
-
تفاوت GZip و Deflate در فشرده کردن
هر دو در استفاده از الگوریتم فشرده سازی دقیقا یکسان هستند و تنها تفاوتی بین آن دو اینستکه :
با استفاده از GZip میتوانید اطلاعات اضافه ای (metadata) را به قسمت header و footer فایل خروجی اضافه نمایید لذا اندکی میتواند حجم خروجی آن از Deflate بیشتر شود.
بعبارت دقیقتر کلاس GZipStream یک لفافه (wrapper) بر روی کلاس DeflateStream است و روش فشردن اطلاعات در هردو کلاس مطابق تعریف RFC 1952 است.
منبع : http://msdn2.microsoft.com/en-us/magazine/cc163727.aspx
-
آغاز کار با کامپوننت ErrorProvider
از این کامپوننت برای نمایش پیغامهای خطا و هشدار در UI استفاده میشود.
private void textBox1_Leave(object sender, EventArgs e)
{
ErrorProvider ep = new ErrorProvider();
if (string.IsNullOrEmpty(textBox1.Text))
ep.SetError(textBox1, "نمیتواند خالی باشد");
else
ep.SetError(textBox1, "");
}
-
برعکس کردن ترتیب آیتمهای یک آرایه
int[] someArray = new int[5] { 1, 2, 3, 4, 5 };
Array.Reverse(someArray);
-
تبدیل آرایه از بایتها به یک رشته و بلعکس
//You have a byte[] representing some binary information, such as a bitmap.
// You need to encode this data into a string so that it can be sent over
// a binary-unfriendly transport, such as email.
public string Base64EncodeBytes(byte[] inputBytes)
{
return (Convert.ToBase64String(inputBytes));
}
//You have a String that containsinformation such asa bitmap encoded
// asbas e64. You need to decode this data (which may have been embedded in an
// email message) from a String into a byte[] so that you can access
// the original binary.
public byte[] Base64DecodeString(string inputStr)
{
byte[] decodedByteArray = Convert.FromBase64String(inputStr);
return (decodedByteArray);
}
منبع : "C# 3.0 Cookbook™, Third Edition"
-
بدست آوردن حروف تشکیل دهنده ی یک رشته
string testStr = "Sinpin";
foreach (char c in testStr)
MessageBox.Show(c.ToString());
string testStr = "Sinpin";
for (int counter = 0; counter < testStr.Length; counter++)
MessageBox.Show(testStr[counter].ToString());
و البته روش اول بهینه تر است.
-
هرس کردن یک رشته متنی
حذف حروف خاص
You have a string with a specific set of characters, such as spaces, tabs, escaped single double quotes, any type of punctuation character(s), or some other character(s), at the beginning and/or end of a string. You want a simple way to remove these characters.
private void PruningCharacters()
{
string foo = "--TEST--";
Console.WriteLine(foo.Trim(new char[] {'-'})); // Displays "TEST"
foo = ",-TEST-,-";
Console.WriteLine(foo.Trim(new char[] {'-',','})); // Displays "TEST"
foo = "--TEST--";
Console.WriteLine(foo.TrimStart(new char[] {'-'})); // Displays "TEST--"
foo = ",-TEST-,-";
Console.WriteLine(foo.TrimStart(new char[] {'-',','})); // Displays "TEST-,-"
foo = "--TEST--";
Console.WriteLine(foo.TrimEnd(new char[] {'-'})); // Displays "--TEST"
foo = ",-TEST-,-";
Console.WriteLine(foo.TrimEnd(new char[] {'-',','})); //Displays ",-TEST"
}
منبع : "C# 3.0 Cookbook™, Third Edition"
-
بدست آوردن تعداد خطوط یک رشته
using System.Text.RegularExpressions;
public static long LineCount2(string source, bool isFileName)
{
if (source != null)
{
string text = source;
long numOfLines = 0;
if (isFileName)
{
using (FileStream FS = new FileStream(source, FileMode.Open,
FileAccess.Read, FileShare.Read))
{
using (StreamReader SR = new StreamReader(FS))
{
while (text != null)
{
text = SR.ReadLine();
if (text != null)
{
++numOfLines;
}
}
}
}
return (numOfLines);
}
else
{
Regex RE = new Regex("\n", RegexOptions.Multiline);
MatchCollection theMatches = RE.Matches(text);
return (theMatches.Count + 1);
}
}
else
{
// Handle a null source here.
return (0);
}
}
منبع : "C# 3.0 Cookbook™, Third Edition"
-
بدست آوردن تک تک مقادیر از یک رشته ی مرکب مرزبندی شده
//Using the Split instance method on the String class, you can place the delimited
//information into an array in as little as a single line of code.
private void GetItemsFromDelimitedString()
{
string delimitedInfo = "100,200,400,3,67";
string[] discreteInfo = delimitedInfo.Split(new char[] { ',' });
foreach (string Data in discreteInfo)
MessageBox.Show(Data);
}
منبع : "C# 3.0 Cookbook™, Third Edition"
-
تغییر نام دادن (Rename) یک فایل
using System.IO;
You need to rename a file.Unfortunately, there isno specific rename method that can be used to rename a file. Instead, you can use the static Move method of the File class or the instance MoveTo method of the FileInfo class. The static File.Move method can be used to rename a file in the following manner:
public static void RenameFile(string originalName, string newName)
{
File.Move(originalName, newName);
}
public static void Rename(FileInfo originalFile, string newName)
{
originalFile.MoveTo(newName);
}
منبع : "C# 3.0 Cookbook™, Third Edition"
-
تبدیل درجه به رادیان و بلعکس
public static double ConvertDegreesToRadians(double degrees)
{
return ((Math.PI / 180) * degrees);
}
public static double ConvertRadiansToDegrees(double radians)
{
return ((180 / Math.PI) * radians);
}
-
تبدیل یک IP به HostName و بلعکس
using System.Net;
public string ConvertIP2HostName(string ip)
{
IPHostEntry iphost = Dns.GetHostEntry(ip);
return iphost.HostName;
}
public string HostNameToIP(string hostName)
{
IPHostEntry iphost = System.Net.Dns.GetHostEntry(hostName);
IPAddress[] addresses = iphost.AddressList;
StringBuilder addressList = new StringBuilder();
foreach (IPAddress address in addresses)
{
addressList.AppendFormat("IP Address: {0};", address.ToString());
}
return addressList.ToString();
}
نحوه ی استفاده :
private void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show( Class4.ConvertIP2HostName("127.0.0.1"));
MessageBox.Show(Class4.HostNameToIP("laptop"));
}
منبع : "C# 3.0 Cookbook™, Third Edition"
-
خواندن خواص (Attribute) یک دایرکتوری
using System.IO;
public static void DisplayDirectoryTimestamps(string path)
{
Console.WriteLine(Directory.GetCreationTime(path). ToString());
Console.WriteLine(Directory.GetLastAccessTime(path ).ToString());
Console.WriteLine(Directory.GetLastWriteTime(path) .ToString());
}
public static void DisplayTimestamps(DirectoryInfo dirInfo)
{
Console.WriteLine(dirInfo.CreationTime.ToString()) ;
Console.WriteLine(dirInfo.LastAccessTime.ToString( ));
Console.WriteLine(dirInfo.LastWriteTime.ToString() );
}
public static void DisplayDirectoryHiddenAttribute(string path)
{
DirectoryInfo dirInfo = new DirectoryInfo(path);
// Display whether this directory is hidden
Console.WriteLine("Is directory hidden? = " +
((dirInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden));
}
منبع : "C# 3.0 Cookbook™, Third Edition"
-
دستکاری خواص (Attribute) یک دایرکتوری
using System.IO;
public static void ModifyDirectoryTimestamps(string path, DateTime dt)
{
Directory.SetCreationTime(path, dt);
Directory.SetLastAccessTime(path, dt);
Directory.SetLastWriteTime(path, dt);
}
public static void ModifyTimestamps(DirectoryInfo dirInfo, DateTime dt)
{
dirInfo.CreationTime = dt;
dirInfo.LastAccessTime = dt;
dirInfo.LastWriteTime = dt;
}
public static void MakeDirectoryHidden(DirectoryInfo dirInfo)
{
// Modify this directory's attributes
dirInfo.Attributes |= FileAttributes.Hidden;
}
منبع : "C# 3.0 Cookbook™, Third Edition"
-
تغییر نام دادن (Rename) یک دایرکتوری
using System.IO;
public static void RenameDirectory(string originalName, string newName)
{
try
{
// "rename" it
Directory.Move(originalName, newName);
}
catch (IOException ioe)
{
// most likely given the directory exists or isn't empty
Console.WriteLine(ioe.ToString());
}
}
منبع : "C# 3.0 Cookbook™, Third Edition"
-
خواندن خواص (Attribute) یک فایل
using System.IO;
public static void DisplayFileTimestamps(string path)
{
Console.WriteLine(File.GetCreationTime(path));
Console.WriteLine(File.GetLastAccessTime(path));
Console.WriteLine(File.GetLastWriteTime(path));
}
public static void DisplayFileInfoTimestamps(FileInfo fileInfo)
{
Console.WriteLine(fileInfo.CreationTime.ToString() );
Console.WriteLine(fileInfo.LastAccessTime.ToString ());
Console.WriteLine(fileInfo.LastWriteTime.ToString( ));
}
public static void DisplayFileHiddenAttribute(string path)
{
if (File.Exists(path))
{
FileInfo fileInfo = new FileInfo(path);
// Display whether this file is hidden
Console.WriteLine("Is file hidden? = " +
((fileInfo.Attributes & FileAttributes.Hidden) ==
FileAttributes.Hidden));
}
}
منبع : "C# 3.0 Cookbook™, Third Edition"
-
دستکاری خواص (Attribute) یک فایل
using System.IO;
public static void ModifyFileTimestamps(string path)
{
File.SetCreationTime(path, DateTime.Parse(@"May 10, 2003"));
File.SetLastAccessTime(path, DateTime.Parse(@"May 10, 2003"));
File.SetLastWriteTime(path, DateTime.Parse(@"May 10, 2003"));
}
public static void ModifyTimestamps(FileInfo fileInfo, DateTime dt)
{
fileInfo.CreationTime = dt;
fileInfo.LastAccessTime = dt;
fileInfo.LastWriteTime = dt;
}
public static void MakeFileHidden(FileInfo fileInfo)
{
// Modify this file's attributes
fileInfo.Attributes |= FileAttributes.Hidden;
}
منبع : "C# 3.0 Cookbook™, Third Edition"
-
گرد کردن و رُند کردن یک مقدار اعشاری
رُند کردن :
int x = (int)Math.Round(2.5555); // x == 3
گرد کردن تا دو رقم اعشار :
decimal x = Math.Round(2.5555, 2); // x == 2.56
-
معرفی روشی بهینه جهت بدست آوردن درخت کامل یک دایرکتوری
You need to get a directory tree, potentially including filenames, extending from any point in the directory hierarchy
using System.IO;
public IEnumerable<FileSystemInfo> GetAllFilesAndDirectories(string dir)
{
DirectoryInfo dirInfo = new DirectoryInfo(dir);
Stack<FileSystemInfo> stack = new Stack<FileSystemInfo>();
stack.Push(dirInfo);
while (dirInfo != null || stack.Count > 0)
{
FileSystemInfo fileSystemInfo = stack.Pop();
DirectoryInfo subDirectoryInfo = fileSystemInfo as DirectoryInfo;
if (subDirectoryInfo != null)
{
yield return subDirectoryInfo;
foreach (FileSystemInfo fsi in subDirectoryInfo.GetFileSystemInfos())
stack.Push(fsi);
dirInfo = subDirectoryInfo;
}
else
{
yield return fileSystemInfo;
dirInfo = null;
}
}
}
منبع : "C# 3.0 Cookbook™, Third Edition"
-
بدست آوردن قسمت صحیح یک عدد اعشاری
decimal d = 123.234M;
decimal i = Math.Truncate(d)
-
یافتن مقادیر ماکزیمم و مینیمم Primitive Type های عددی
این مقادیر بصورت خواص درونکار وجود دارند.
برای مثال :
Int16.MaxValue;
Int16.MinValue;
Int64.MaxValue;
Int64.MinValue;
Double.MaxValue;
Double.MinValue;
...
-
به توان رساندن و جذر گرفتن
double i = Math.Pow(4, 2); // = 16;
double j = Math.Pow(4, .5); // = 2;
پارامتر اول : عدد دلخواه
پارامتر دوم : توان عدد (از اعداد بین 0 تا 1 برای جذر گرفتن استفاده کنید)
-
روش بررسی خالی بودن یک رشته
string str;
if (string.IsNullOrEmpty(str))
{
...
}
و یا :
string str;
if (str.Trim() == "")
{
...
}
و یا :
string str;
if (str == string.Empty)
{
...
}
استفاده از روش اول توصیه شده است.
-
مرتب سازی آیتمهای یک ارایه
int[] array ={ 4, 10, 17, 5, 1 };
Array.Sort(array);
-
یافتن مکان کرسر و متن انتخاب شده در یک TextBox
خاصیت SelectionStart از کنترل TextBoxBase یک عدد برمیگرداند که معادل مکان فعلی کرسر است :
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
this.Text = textBox1.SelectionStart.ToString();
}
یافتن رشته انتخاب شده در یک تکست باکس :
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(textBox1.SelectedText);
}
یافتن طول رشته انتخاب شده :
int n = textBox1.SelectionLength;
-
انتقال آیتمهای یک کالکشن به یک آرایه
ArrayList list = new ArrayList();
list.Add(new Employee());
list.Add("farzaneh");
list.Add(1);
object[] array = new object
[list.Count];
list.CopyTo(array, 0);
-
سوییچ کردن بین حالتهای مختلف یک ListView
private void button2_Click(object sender, EventArgs e)
{
int n = (int) listView1.View;
if (n == 4)
n = -1;
listView1.View = (View)Enum.ToObject(typeof(View), ++n);
}
-
معکوس کردن عملکرد دکمه های جهت نما روی یک TextBox
با زدن دکمه جهت نمای چپ کرسر چشمک زن به سمت راست میرود و بلعکس :
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Left:
e.Handled = true;
if (textBox1.SelectionStart <= textBox1.Text.Length - 1)
textBox1.SelectionStart++;
break;
case Keys.Right:
e.Handled = true;
if (textBox1.SelectionStart >= 1)
textBox1.SelectionStart--;
break;
}
}
-
یک روش ساده برای افزودن تصویر به TextBox
private void Form1_Load(object sender, EventArgs e)
{
PictureBox pic = new PictureBox();
//pic.Image = Image.FromFile("آدرس فایل");
pic.Image = SystemIcons.Information.ToBitmap();;
textBox1.Controls.Add(pic);
}
-
ریست کردن مقدار یک فیلد Identity در SQL Server
ابتدا جدول مورد نظر رو خالی کرده :
DELETE FROM <table name>
و سپس کوئری زیر را روی آن اجرا نمایید :
DBCC CHECKIDENT (<table name>, RESEED, 0)
منبع : http://blogs.microsoft.co.il/blogs/m...ql-server.aspx
-
معرفی یک لینک برای مشاهده ی انواع ConnectionString ها
-
تولید رشته های منحصر بفرد
در ساده ترین حالت اینکار معمولا از طریق GUID انجام میشود :
private string GenerateId1()
{
return Guid.NewGuid().ToString();
}
نمونه ای از خروجی:
نقل قول:
c1eab2fa-63bb-426f-a2ff-dd87b03c0aa0
یک الگوریتم دیگر :
private string GenerateId2()
{
long i = 1;
foreach (byte b in Guid.NewGuid().ToByteArray())
{
i *= ((int)b + 1);
}
return string.Format("{0:x}", i - DateTime.Now.Ticks);
}
نمونه ای از خروجی:
نقل قول:
4f2014c22f7c88ea
یک الگوریتم دیگر :
private long GenerateId3()
{
byte[] buffer = Guid.NewGuid().ToByteArray();
return BitConverter.ToInt64(buffer, 0);
}
نمونه ای از خروجی :
نقل قول:
5209165259893891216
منبع : http://www.csharphelp.com/archives4/archive691.html
-
جایگزین کردن یک رشته درون متن یک textbox به روش اندیس دهی
با فشار دادن دکمه،زیررشته ی موجود در تکس باکس که از اندیس 12 شروع می شود با *** جایگزین می شود
privatevoid button1_Click(object sender, EventArgs e)
{
textbox1.SelectionStart = 0;
textbox1.SelectionLength = textbox1.Text.Length;
textbox1.Text=textbox1.SelectedText.Insert(12, "***");
}
-
بدست آوردن لیست IP های یک سیستم
using System.Net;
برای سیستم لوکال :
IPAddress[] ipList = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress ip in ipList )
MessageBox.Show(ip.ToString());
برای یک سیستم خاص با دانستن نام آن :
IPAddress[] ipList = Dns.GetHostAddresses("Sinpin");
foreach (IPAddress ip in ipList )
MessageBox.Show(ip.ToString());
-
بدست آوردن نام سیستم لوکال
string pcName = Environment.MachineName;
و یا :
using System.Net;
string pcName = Dns.GetHostName();
-
غیر فعال کردن یک رویداد در زمان اجرا
گاهی لازم است در زمان اجرا یک رویداد رو موقتا و یا برای همیشه غیر فعال کنیم. برای اینکار با استفاده از =- ایونت هندلر مورد نظر را از رویداد حذف میکنیم.
مثال - فرض کنید که در جایی لازم است مقدار یک TextBox رو عوض کنیم بدون آنکه بخواهیم رویداد TextChanged آن تحریک شود (البته در اینجا بصورت موقت و بعد از تخصیص مقدار آن را به حالت اول برمیگردانیم) :
private void button1_Click(object sender, EventArgs e)
{
// remove event handler
textBox1.TextChanged -= new EventHandler(textBox1_TextChanged);
textBox1.Text = "salam";
// add event handler
textBox1.TextChanged += new EventHandler(textBox1_TextChanged);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
....
MessageBox.Show("TextChanged");
....
}
-
بدست آوردن لیست تمامی فونتهای نصب شده در سیستم
using System.Drawing.Text;
InstalledFontCollection fonts = new InstalledFontCollection();
foreach (FontFamily font in fonts.Families)
listBox1.Items.Add(font.Name);
-
تغییر رنگ و فونت متن انتخاب شده در یک RichTextBox
richTextBox1.SelectionFont = new Font(richTextBox1.Font,
FontStyle.Bold | FontStyle.Underline);
richTextBox1.SelectionColor = Color.Red;
-
معرفی سایتهایی جهت دریافت آیکن رایگان
-
تبدیل عدد و رشته به متناظر بولین آنها و بلعکس
تبدیل یک متغیر بولین به نوع صحیح :
bool flag = false;
int i = (flag ? 1 : 0);
تبدیل یک عدد صحیح به متناظر بولین آن :
int i = 1;
bool flag = (i == 1 ? true : false);
تبدیل یک رشته به متناظر بولین آن :
string str = "Yes";
bool flag = str.ToLower() == "yes" ? true : false;
-
انجام محاسبات بر روی یک فیلد از DataTable
myDataset.Table["myTable"].Compute("Sum(myFiledname)","FilterCreatia");
-
برقراری ارتباط تلفنی (Dial up) توسط TAPI32
add Reference Microsoft.TAPI32
TAPI32Lib.RequestMakeCall rmc = new TAPI32Lib.RequestMakeCall ();
rmc.MakeCall("Home","09173.....","0","none");