بستخدام الخاصية Environment.TickCount نستطيع معرفة الوقت المنقضي للتشغيل بأجزاء الثواني , بإمكانك الإستفادة من هذه الخاصية فيما بعد لعمل برنامج يقوم بعمل تقارير اوقات التشغيل للجهاز والوقت المنقضي للتشغيل ,
تقوم الميثود التالية بحساب الوقت المنقضي للتشغيل و ارجاع قيمة String تحتوي على الساعات و الدقائق ...
للبحث بين هذه الأكواد قم بضغط على المفتاحين
Control + F
----------------------------------------for loop & if condition
using System;
class Class1
{
public static void Main()
{
for (int i=0;i<5;i++){
if (i == 3) continue; // if (break mean end loop
Console.WriteLine (i);}
}
} /// the output is : 0 1 2 4
---------------------------------------------while loop:
using System;
class Class1
{
public static void Main()
{int i=0;
while (i<5){i++;
if (i == 3) continue;
Console.WriteLine (i);}
}
}/* -------> the out put is : 1245 */
---------------------------------------------do while loop:
using System;
class Class1
{
public static void Main()
{
int i=0;
do
{
i++;
if (i == 3) continue;
Console.WriteLine (i);
}
while (i<5);
}
}/* -------> the out put is : 1245 */
---------------------------------------------- foreach & Array
using System; // this program count the odd and even numbers within array :
class MainClass
{
public static void Main()
{
int odd = 0, even = 0;
int[] arr = new int [] {0,1,2,5,7,8,11};
foreach (int i in arr)
{
if (i%2 == 0)
even++;
else
odd++;
}
Console.WriteLine("Found {0} Odd Numbers, and {1} Even Numbers.",
odd, even);
}
} //The Output is :Found 4 Odd Numbers, and 3 Even Numbers.
----------------------------------------enum:
using System;
class Class1
{
enum color {red,green,blue}
public static void Main()
{
color c;
c=color.blue;
Console.WriteLine (c);
}
}
----------------------------------------- Working With Functions
- functions & functions call
- Access Modifier ( public , privit , protected )
- call static function and static class
-------------------------------functions & functions call EX:
using System;
class A
{
// Public Global Variable You Can Call This Variable From Any Class
public static int q=3;
static void Main()
{
//A y=new A(); //Creat y Object
//B z=new B(); // Creat z Object
http://z.xxx(); // Call Function xxx By Using z Object
Console.WriteLine (xxx ()+2); // function Call Without Object
}
// Use public to Allow Call This Function out main Class
// Use Static to Call Function Without Creat Object
public static int xxx()
{int z=10; return z;}
}
/*class B
{
public void xxx()
{A a=new A(); // Creat a Object
a.xxx(); // Call Function xxx By Using a Object
Console.WriteLine (a.q );} // Call Global Variable From Main Class
}*/
-----------------------------------------OOP :1-overload
وهي وجود اكثر من فنكشن تحمل نفس الأسم داخل الكلاس بحيث تختلف اما في الداتا تايب او في عدد الباراميترات
using System;
class a
{
static void Main()
{
C c=new C();
c.max(5,5);
c.max ('a','b');
}
public class d
{
public void yyy()
{
}
}
}
class b
{
void xxx()
{
a.d a=new a.d();
a.yyy ();
}
}
class C
{ // overload, tow functions have the same name
public int max(int x,int y)
{
if (x>y) return x; else return y;
}
public char max(char a,char b)
{
return a;
}
}
------------------------------------------------------- overload Ex:2
using System;
class A
{
static void Main()
{
int x=int.Parse (Console.ReadLine ());
int y=int.Parse (Console.ReadLine ());
Console.WriteLine (sum(x,y));
Console.WriteLine (sum(2.1f,2.5f));
}
static int sum(int x,int y)
{ return x+y; }
static float sum(float q,float w)
{return q+w;}
}
------------------------------------------------- boxing & Casting
كيفية تعريف اوبجكت وتحويلة الى اي نوع من الداتا تايب
using System;
class A
{
static void Main()
{
object o;
int y;
string s;
o=19;
y=(int) o;
o="main";
s=(string) o; Console.WriteLine (y + " " + s);
}
}
-------------------------------------------------OOP: 2-Inheritance
خاصية الوراثة مهمة جدا كونك تستطيع الوصول الى الميثودس الخاصة بكلاس الاب بدون الحاجة الى اعادة كتابة الكود مرة اخرى
using System;
class MC
{
static void Main()
{
A a=new A ();
B b=new B();
b.x=5;
b.y=3;
a.x=3;
}
}
class A
{
public A()
{
Console.WriteLine ("aaa");
}
public int x;
}
class B:A
{
public B()
{
Console.WriteLine ("bbb");
}
public int y;
}
-----------------------------------------------------interface Ex:1
using System;
class MC
{
static void Main()
{
A a=new A ();
B b=new B();
b.x=5;
b.y=3;
b.fun();
}
}
class A
{
public A()
{
Console.WriteLine ("aaa");
}
}
interface D
{
void fun();
}
class B:A,D
{
public B()
{
Console.WriteLine ("bbb");
}
public int y;
public int x;
public void fun()
{
Console.WriteLine ("Hello");
}
}
-----------------------------------------------interface EX:2
using System;
class MC
{
static void Main()
{
A a=new A ();
B b=new B();
b.x=5;
b.y=3;
b.fun();
b.fun2 ();
}
}
class A
{
public A()
{
Console.WriteLine ("aaa");
}
}
class B:A,D
{
public B()
{
Console.WriteLine ("bbb");
}
public int y;
public int x;
public void fun(){Console.WriteLine ("Hello Fun1");}
public void fun2(){Console.WriteLine ("Hello Fun2");}
}
interface D:F
{
void fun();
}
interface F
{
void fun2();
}
-----------------------------------------interface EX3:
using System;
class Class1
{
static void Main()
{
B b = new B();
b.xxx();
}
}
interface A
{
void xxx();
}
class B:A
{
public void xxx()
{
Console.WriteLine ("Hello");
}
}
-----------------------------// three interfaces inherited Ex4:
using System;
class Class1
{
static void Main()
{
B b = new B();
b.xxx1();
b.xxx2();
b.xxx3();
}
}
interface A
{
void xxx1();
}
interface AA:A
{
void xxx2();
}
interface AAA:AA
{
void xxx3();
}
class B:A
{
public void xxx1()
{Console.WriteLine ("Hello1");}
public void xxx2()
{Console.WriteLine ("Hello2");}
public void xxx3()
{Console.WriteLine ("Hello3");}
}
-------------------------------------------
نوع من الفنكشن لايمكن ان يورث
sealed -->this mean that class cannot be inheritened
Ex : sealed class a{ void main(){} }
------------------------------------------- abstract class
using System;
class MC
{
static void Main()
{
A a=new A ();
a.xxx (); // abstract class cannot get any object from it
} // if it was inherited or not
}
abstract class A // if we remove abstract word the program will run
{
public A()
{
}
public void xxx(){Console.WriteLine ("Hello");}
}
class B:A
{
public B()
{
}
} // The output here is Error msg Because we try to call function from abstract class
---------------------------------OOP :3-virtual function & override
يتم تنفيذ الفنكشن الأفتراضية في حالة عدم تطابق شروط الاوفر رايد
using System;
class MC
{
static void Main()
{
A a=new B (); // creat a object from A class that has the size of B clss
a.xxx(); // call virtual function or override function if existing
}
}
class A
{
public A() // Construct Function
{
}
public virtual void xxx() // Virtual Function Called in this Examble if no found override function
{ Console.WriteLine ("aaa");}
}
class B:A // Class B Inherited from A Class
{
public B() // Construct Function
{
}
public override void xxx()// override function that called in this //Examble
{Console.WriteLine ("bbb");}
}
-----------------------------------------------------Refrance
تبقى قيمة المتغير محفوظة في الذاكرة حتى بعد تنفيذ الفنكشن
using System;
class MC
{
static void Main()
{
int y=3;
MC m=new MC ();
m.xxx (ref y); // call 1 x=x+1
m.xxx (ref y);// call 2 x=x+1
m.xxx (ref y);// call 3 x=x+1
}
public void xxx(ref int x) // ref mean save the value of x when exit from fuction
{ x++; Console.WriteLine (x);}
// the output with ref is: 4 5 6
// the output without ref is: 4 4 4
}
--------------------------------------------------- out
using System;
class MC
{
static void Main()
{
int y;
MC m=new MC ();
m.xxx (out y); // print the value of y from variable x
// use out to Allow Compiler to installaize the variable in other function
}
public void xxx(out int x)
{ x=3; Console.WriteLine (x);}
}
--------------------------------------------------- params
using System;
class MC
{
static void Main()
{
MC m=new MC ();
m.xxx (10,20,30); // insert more then value in function that has one Parameter
}
public void xxx(params int[] x) // insert the values in Array
{
int z=0;
for (int i=0; i<x.Length; i++)
z=z+x[i];
Console.WriteLine (z);}}
-------------------------------------------------Args :
يمكن الأستفادة منها في حالة اذا اردنا اتباع اوامر اخرى بعد كتابة اسم الملف الذي نريد تنفيذه
using System;
class MC
{
static void Main(string [] args)
{
int q=0;
if (args.Length >0)
{
for (int i=0;i<args.Length;i++)
{
int z=int.Parse (args[i]);
q+=z;
}
Console.WriteLine (q);
}
else Console.WriteLine ("no input");
}
}
-------------------------------------------------Exception :
تستخدم الاستثنائات لسيطرة على الاخطاء التي يمكن ان تحدث اثناء تنفيذ الكود
using System; //Examble 1
class MC
{
static void Main()
{
int x,y,z;
x= int.Parse ( Console.ReadLine ());
y= int.Parse ( Console.ReadLine ());
try
{
z=x/y;
}
catch (Exception)
{
Console.WriteLine ("Error1");
}
}
}
----------------------------------------------------
using System; //Examble 2
class MC
{
static void Main()
{
int x,y,z;
x= int.Parse ( Console.ReadLine ());
y= int.Parse ( Console.ReadLine ());
try
{
z=x/y;
}
catch (Exception e)
{
Console.WriteLine (e.Message);
}
}
}
--------------------------------------------------
using System; //Examble 3
class MC
{
static void Main()
{
int x,y,z;
x= int.Parse ( Console.ReadLine ());
y= int.Parse ( Console.ReadLine ());
try
{
z=x/y;
}
catch (DivideByZeroException)
{
Console.WriteLine ("Error1");
}
catch (Exception e)
{
Console.WriteLine (e.Message);
}
finally
{
Console.WriteLine ("Error finally");
}
}
}
--------------------------------------------checked overflow
using System;
class MC
{
static void Main()
{
int x,y,z;
try
{
checked
{ z=int.MaxValue;
Console.WriteLine (z);
z++;
Console.WriteLine (z);}
}
catch (Exception e)
{
Console.WriteLine (e.Message); } } }
--------------------------------------------string
using System;
class MC
{
static void Main()
{
string a="main jitawi";
char f1= a[2];
Console.WriteLine(f1);
string b="c is great";
string b2=b.Insert(2,"sharp");
Console.WriteLine(b2);
string msg="hello";
int c=msg.Length;
Console.WriteLine(c);
string d="hello";
string d2=string.Copy (d);
Console.WriteLine(d2);
string e=string.Concat ("a","b","c","d");
Console.WriteLine(e);
string e2=string.Concat ("a"+"b"+"c"+"d");
Console.WriteLine(e2);
string e3 = "a"+"b"+"c"+"d";
Console.WriteLine(e3);
}
}
---------------------------------------------Refliction
using System; // use this program to know info about string methods
using System.Reflection;
class MC
{
static void Main()
{
Type t=typeof(byte);
Console.WriteLine("Type:{0}",t);
Type t1=typeof(string);
MethodInfo [] mi=t1.GetMethods();
foreach (MethodInfo m in mi)
{ Console.WriteLine("Method:{0}",m);}
}}
--------------------------------------------------File
القرائة و الكتابة على ملف تكست
using System;// get strings from Text File
using System.IO; // and write Strings on Text File
class A
{
static void Main()
{
StreamReader reder = new StreamReader("c:\\ali1.txt");
StreamWriter writer = new StreamWriter("c:\\ali2.txt");
string line;
while((line = reder.ReadLine())!=null)
{writer.WriteLine(line);}
reder.Close();
writer.Close();
}
}
-----------------------------------------namespace
التعامل مع النيم سبيس
using System;
namespace xxx
{
class A
{
static void Main()
{
yyy.zzz.B b=new yyy.zzz.B ();
b.fun ();
}
}
}
namespace yyy
{
namespace zzz
{
class B
{
public void fun(){Console.WriteLine("Hello");}
}
}}
-------------------------------------------unsafe code
استخدام البوينترز في السي شارب
using System;// Allow to useing pointers with C#
namespace xxx
{
class A
{
static void Main()
{
yyy.zzz.B b=new yyy.zzz.B ();
b.fun ();
}
}
}
namespace yyy
{
namespace zzz
{
class B
{
unsafe public void fun(){int a=5;int *p=&a;Console.WriteLine(*p);}
}
}}
---------------------------------------------Proparity Ex:1
كيفية عمل بروبرتي في السي شارب
using System;
class A
{
static void Main()
{
B b = new B();
b.fun();
Console.WriteLine (x);
}
static private int x;
public void set_xxx(int i) {x=i;}
}
class B
{
public void fun()
{
A a=new A();
a.set_xxx (5);
}}
----------------------------------------------------Proparity Ex:2
using System;
class A
{
static void Main()
{
B b = new B();
b.fun();
}
static private int x;
public void set_xxx(int i) {x=i;}
public int get_xxx(){return x;}
}
class B
{
public void fun()
{
A a=new A();
a.set_xxx (5);
Console.WriteLine (a.get_xxx());
}
}
-----------------------------------------------Proparity Ex:3
using System;
class A
{
static void Main()
{
B b = new B();
b.fun();
}
private int name;
public int Name{ set{name=value;} get{return name;}
}
}
class B
{
public void fun()
{
A a=new A();
a.Name=5;
Console.WriteLine (a.Name);
}}
-------------------------------------------------delegate
using System;
class A
{
public delegate void qq();
static void Main()
{
qq q=new qq (xxx);
q();
q=new qq (yyy);
q();
q=new qq (zzz);
q();
}
public static void xxx(){Console.WriteLine ("xxxxxx");}
public static void yyy(){Console.WriteLine ("yyyyyy");}
public static void zzz(){Console.WriteLine ("zzzzzz");}
}
----------------------------------------------- Delegate Ex:2
using System;
class A
{
public delegate void xxx(int a,int b);
static void Main()
{
xxx q=new xxx (fun2);
q(2,12);
A a =new A ();
q = new xxx (a.fun1 );
q(3,4);
D d=new D();
q= new xxx (d.fun3 );
q(8,9);
}
public void fun1(int x,int y)
{int z;z=x+y;Console.WriteLine (z);}
public static void fun2(int x,int y)
{int z;z=x*y;Console.WriteLine (z);}
}
class D
{
public void fun3(int x,int y)
{Console.WriteLine (x);}}
--------------------------------------------------------event
using System;
public delegate void A();
class B
{
public event A C;// declaration event C
public void D() {C();}
}
public class E
{
static private void f(){ Console.WriteLine ("Hello");}
static public void x() {Console.WriteLine ("Hello2");}
static void Main()
{
B b=new B ();
b.C +=new A;// store the output of function f in event C
b.C +=new A(x);// store the output of function x in event C
b.D ();//call D function to Veiw the event stores
}
}
----------------------------------------------------------this
/*call any External object function or variable from the same class without make object to call it,cannot uses with static functions or static variables ,can be used to access members from within constructors.*/
using System;
public class A
{
int x=34;
public static void Main()
{
A a=new A ();
a.fun ();
}
public void fun()
{
Console.WriteLine (this.x );
}
}
----------------------------------------------------------index
using System;
class BookIndexor
{
private int [] bookcollection = new int [50];
//b[3]
public int this [int index]
{
get
{
if (index<0||index>=50) return 0;
else return bookcollection[index];
}
set
{if (!(index<0||index>=50))bookcollection[index]=value;}
} //3 256
}
public class MainClass
{
public static void Main()
{
BookIndexor b=new BookIndexor ();
b[3]=256;
for (int i=0;i<=3;i++)
{
Console.WriteLine ("Book Collection #{0}={1}",i,b[i]);
}
}
}
------------------------------------------------------------------------------------------------------------
التعامل مع قواعد البيانات
using System; ADO.NET Consol Example
using System.Data;
using System.Data.OleDb;
namespace ADODotNet
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
OleDbConnection myConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;DataSource=Test.MDB");
// open connection
myConnection.Open();
//to Create DataAdapter object for upadte or other operation
OleDbDataAdapter myAdapter=new OleDbDataAdapter("SELECT * FROM Table1",myConnection);
OleDbCommandBuilder myBuild=new leDbCommandBuilder(myAdapter);
//to Create DataSet to contain related data tables,rows and columns
DataSet myDataSet=new DataSet();
//to Fill DataSet from Table1
myAdapter.Fill(myDataSet,"Table1");
/*set up keys object for defining primary key
*Before you using find we have to set up a primary you'll use during searching */
DataColumn[] keys=new DataColumn[1];
keys[0]=myDataSet.Tables["Table1"].Columns["Column1"];
myDataSet.Tables["Table1"].PrimaryKey=keys;
DataRow findRow=myDataSet.Tables["Table1"].Rows.Find("mazy");
if(findRow==null)
{
Console.WriteLine("mazy,not found and I'll add it to table");
DataRow myRow=myDataSet.Tables["Table1"].NewRow();
myRow["Column1"]="mazy";
myRow["Column2"]="Hello everybody!";
myDataSet.Tables["Table1"].Rows.Add(myRow);
if((findRow=myDataSet.Tables["Table1"]
.Rows.Find("mazy"))!=null)
Console.WriteLine("mazy,successfully added to Table1");
}
Else
{
Console.WriteLine("mazy,already present in database");
}
myAdapter.Update(myDataSet,"Table1");
myConnection.Close();
}}}
-------------------------------------------------------------------
برنامج شات مبسط بستخدام الكونسول
using System; Socket Example – Server Code
using System.Text;
using System.Net;
using System.Net.Sockets;
public class serv
{
public static void Main()
{
Console.WriteLine("Finding Client...");
xxx:
try
{
IPAddress ipAd = IPAddress.Parse("192.168.0.2"); //use local m/c IP adds, and use the same in the client
TcpListener myList=new TcpListener(ipAd,8001);
myList.Start();
Socket s=myList.AcceptSocket();
Console.Write("Message From " + ipAd + ": ");
byte[] b=new byte[100];
int k=s.Receive(b);
for (int i=0;i<k;i++)
Console.Write(Convert.ToChar(b[i]));
Console.WriteLine ("");
ASCIIEncoding asen=new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
s.Close();
myList.Stop();
goto xxx;
}
catch (Exception)
{
goto xxx;
}
}
}
using System; Socket Example – Client Code
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
public class clnt
{
public static void Main()
{
Console.Write("Connecting.....");
xxx:
try
{
TcpClient tcpclnt = new TcpClient();
Console.Write(".");
tcpclnt.Connect("192.168.0.2",8001); // use the ipaddress as in the server program
Console.WriteLine("Connected");
Console.Write("Enter Your Message : ");
String str=Console.ReadLine();
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen= new ASCIIEncoding();
byte[] ba=asen.GetBytes(str);
Console.WriteLine("Transmitting.....");
stm.Write(ba,0,ba.Length);
byte[] bb=new byte[100];
int k=stm.Read(bb,0,100);
for (int i=0;i<k;i++)
Console.Write(Convert.ToChar(bb[i]));
if (str=="end") tcpclnt.Close();
else
goto xxx;
}
catch (Exception)
{
goto xxx;
}
}
}
التعامل مع ال Controls في ال Windows Applications
كود
Rich Text Box
// to set rich text box fill on the form
richTextBox2.Dock = DockStyle.Fill;
// to load file from drive C:\ into buffer by using rich text box
richTextBox2.LoadFile("C:\\mmm.rtf");
// to load file from any path
FileDialog ff;
ff=new OpenFileDialog();
ff.ShowDialog();
string ss=ff.FileName.ToString();
richTextBox2.LoadFile(ss);
// to change the text font at the rich text box
richTextBox2.Font = new Font("Verdana", 12, FontStyle.Italic);
//to change the text color at the rich text box
richTextBox2.ForeColor = Color.Red;
// to display the content of the buffer into rich text box
Controls.Add(richTextBox2);
// to save the content of rich text box into file at drive C:\
richTextBox2.SaveFile("C:\\MyDocument.rtf",RichTextBoxStreamType.RichText);
// to save as by setting file name , file type and its path
FileDialog ff;
ff=new SaveFileDialog();
ff.ShowDialog();
string ss=ff.FileName.ToString();
richTextBox2.SaveFile(ss, RichTextBoxStreamType.RichText);
//to perform searching to find any word occurs at the rich text box
richTextBox2.Find(textBox1.Text, RichTextBoxFinds.MatchCase);
//to change the font of the selection word
richTextBox2.SelectionFont = new Font("Verdana", 12, FontStyle.Bold);
//to change the font color of the selection word
richTextBox2.SelectionColor = Color.Blue;
//to clear all the content of the rich text box
richTextBox2.ResetText();
//to select all the content of the rich text box
richTextBox2.SelectAll();
//to make hyper link with internet we must insert LinkClicked rich text box handler into your project
private void richTextBox2_LinkClicked(object sender,System.Windows.Forms.LinkClickedEventArgs e)
{
System.Diagnostics.Process.Start(e.LinkText);
}
//and the system construct the following object through constructor call.
this.richTextBox2.LinkClicked += new System.Windows.Forms.LinkClickedEventHandler(this.richTextBox2_LinkClicked);
// we use menu item with the check property, if it is checked previously or not then we change it into un checked and set text attribute at the rich text box into read only else we change it into checked and set text read and write
if(menuItem8.Checked) {
menuItem8.Checked=false;
richTextBox2.ReadOnly= false;
}
else {
menuItem8.Checked=true;
richTextBox2.ReadOnly= true;
}
Radio and Check Box
//we use sender obj to check if we select radio button 1 or radio button 2
private void radioButton1_CheckedChanged(object sender, System.EventArgs e)
{
if(sender == radioButton1)
xx=0;
else if(sender == radioButton2)
xx=1;
}
// we call checked property by the radio button object and check its value if it is true or false. This process is used to fix which radio control is selected
private void radioButton3_Click(object sender, System.EventArgs e)
{
if(radioButton3.Checked)
MessageBox.Show("r3");
else if(radioButton4.Checked)
MessageBox.Show("r4");
}
// call checked by the check box object and show if we checked or not
private void checkBox1_CheckedChanged(object sender, System.EventArgs e)
{
if(checkBox1.Checked)
MessageBox.Show("hhhh");
}
ListBox & ComboBox
// To assign selected text value from combo or list box to text box control
textBox1.Text=comboBox2.Text;
textBox1.Text=listBox1.Text;
//To add an item to a list or combo box control
listBox1.Items.Add(textBox1.Text);
comboBox1.Items.Add(textBox1.Text);
//To remove an item from a list or combo box control
listBox1.Items.Remove(textBox1.Text);
comboBox1.Items.Remove(textBox1.Text);
//To remove an item at the 3rd location of the list or combo box control
listBox1.Items.RemoveAt(2);
comboBox1.Items.RemoveAt(2);
//To insert an item at the 4th location of the list or combo box
listBox1.Items.Insert(3,"NAMEER");
comboBox1.Items.Insert(3,"NAMEER");
Painter and Mouse Events
// Using window message Mouse Event Handling (MouseDown button) to set mouse location by the object e of the MouseEvent class and set true to the paint status
private void Painter_MouseDown(object sender,System.Windows.Forms.MouseEventArgs e )
{
xx=e.X;
yy=e.Y;
shouldPaint = true; //paint status
}
// Using window message Mouse Event Handling (MouseUp button) to set false to paint status
private void Painter_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e )
{
shouldPaint = false;
}
// using window message Mouse Event Handling (MouseMove), if the paint status is true then perform painting else not paint
protected void Painter_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
if ( shouldPaint ) {
Pen p=new Pen(Color.Black); // set pen style and pen color
Graphics g = CreateGraphics(); // create graphics object to call graphical //function
SolidBrush sb=new SolidBrush(Color.Red); // set brush color
/*either */ g.FillEllipse(new SolidBrush( Color.Red) ,e.X, e.Y,10, 10);
/* Or */ g.FillEllipse(sb ,e.X, e.Y,150, 150);
g.FillRectangle(sb ,e.X, e.Y,150, 150);
g.DrawLine(p,xx,yy,e.X,e.Y);
xx=e.X;
yy=e.Y;
g.DrawEllipse(p,e.X,e.Y,150,115);
g.DrawPie(p,e.X,e.Y,50,50,0,360); // (pen,e.X,e.Y,starting point(50,50),from angle = 0 to angle =360)
g.DrawRectangle(p,e.X,e.Y,150,115);
}
}
Build Button&TextBox at RunTime
// declared two objects from types TextBox and Button respectively
private System.Windows.Forms.TextBox myTextBox;
private System.Windows.Forms.Button button2;
//create at a runtime new textbox and new button when we click button 5
private void button5_Click(object sender, System.EventArgs e)
{
myTextBox = new TextBox();
myTextBox.Location = new Point (30, 20); // set position of myTextBox
Controls.Add (myTextBox); // Put the myTextBox on the form.
button2 = new Button();
button2.Location = new Point (100, 100); //set position of button2
button2.Size = new System.Drawing.Size(100, 100); // set the size
Controls.Add (button2); // Put the button2 on the form.
button2.Text="ADD";// set label on button2
button2.Click += new EventHandler(button2_Click); //create EventHandler to the button2
}
// Apply window message MouseUp and using event handler object e to check which mouse button is clicked up
private void Form1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
// Show is a static method of System.Windows.Forms.MessageBox
MessageBox.Show ("Right up Click!");
if (e.Button == MouseButtons.Left)
// Show is a static method of System.Windows.Forms.MessageBox
MessageBox.Show ("Left up Click!");
}
Timer
private System.Windows.Forms.Timer timer1;
//changing timer property at the runtime
private void button1_Click(object sender, System.EventArgs e)
{
timer1 = new Timer(); //Create Timer Object
timer1.Interval = 1000; // set one second time interval
timer1.Enabled = true; // to start timer
}
// Or using start function under setting of the timer properties
private void button1_Click(object sender, System.EventArgs e)
{ timer1.Start();
timer1.Tick += new EventHandler (timer1_Tick); // call function for each second according to interval property setting
Using Stop() function
private void button2_Click(object sender, System.EventArgs e)
{
timer1.Stop();
}
TextBox and Font properties
private void menuItem2_Click(object sender, System.EventArgs e)
{
int x=int.Parse(textBox1.Text);
x+=10;
textBox1.Text=x.ToString();
}
private void button1_Click(object sender, System.EventArgs e){
http://textBox1.Font=new Font(textBox1.Font.Name, textBox1.Font.Size ,textBox1.Font.Style ^ FontStyle.Italic);
textBox1.Font=new Font("Arial",14,FontStyle.Bold);
FontConverter.FontNameConverter
ColorDialog cc=new ColorDialog();
cc.ShowDialog();
textBox1.ForeColor=cc.Color;
textBox2.Visible=false;
}
private void button2_Click(object sender, System.EventArgs e)
{
textBox1.Font=new Font("Comic Sans MS",36,FontStyle.Bold);
textBox1.Clear();
textBox1.Focus();
textBox1.AppendText("NAMEER");
FontDialog b=new FontDialog();
b.ShowDialog();
textBox1.Font=b.Font;
ColorDialog cc=new ColorDialog();
cc.ShowDialog();
textBox1.ForeColor=cc.Color;
http://textBox1.BackColor=Color.Red;//Color.DarkRed;
http://textBox1.ForeColor=Color.Blue;
textBox1.TextAlign=HorizontalAlignment.Right;
int n= textBox2.Text.Length;
textBox3.Text=n.ToString();
}
private void button3_Click(object sender, System.EventArgs e)
{
button1.Text="ADD";
ColorDialog cc=new ColorDialog();
cc.ShowDialog();
button1.ForeColor=cc.Color;
FontDialog b=new FontDialog();
b.ShowDialog();
button1.Font=b.Font;
if(button1.Text=="ADD")
button2.Text="MUL";
button1.Enabled=false;
}
private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
// Show is a static method of System.Windows.Forms.MessageBox
MessageBox.Show ("Right Click!");
}
private void gg_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
// Show is a static method of System.Windows.Forms.MessageBox
MessageBox.Show ("Left Click!");
}
Check List Box
Set selection item into item variable, and check if your action is checked or not if yes, set item into list box else remove item from list box.
private void inputCheckedListBox_ItemCheck(object sender, System.Windows.Forms.ItemCheckEventArgs e)
{
string item = inputCheckedListBox.SelectedItem.ToString();
// if(e.NewValue==CheckState.Checked)
/* or using */ if(e.NewValue.ToString()=="Checked")
displayListBox.Items.Add( item );
else
displayListBox.Items.Remove( item );
}
Using SelectedIndexChanged event handling to perform operations on the checkedListBox control.
private void checkedListBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
string item=checkedListBox1.SelectedItem.ToString();
if(checkedListBox1.CheckedItems.ToString()=="ADD")
{
int n=int.Parse(textBox1.Text)+int.Parse(textBox2.Text);
textBox1.Text=n.ToString();
}
if(checkedListBox1.CheckedItems.ToString()=="MUL")
{
int n=int.Parse(textBox1.Text)*int.Parse(textBox2.Text);
textBox1.Text=n.ToString();
}
}
لتشغيل ملف صوت في السي شارب قم بإضافة ما يلي :
Play Wave Sound
اولا :
كود
using System.Runtime.InteropServices;
ثانيا نعرف دالة كالأتي :
كود
[DllImport("winmm.dll")]
private static extern int PlaySoundA(string a,int b , int c);
ثالثا نستدعي الدالة في زر أمر كالتالي :
كود
PlaySoundA(@"file name here",0,0);
مجموعة اكواد لتعامل مع المصفوفات - Array
كود
public class Matrices
{
public static decimal[,] minuplate( decimal[,] a, decimal[,] B)// ضرب المصفوفات
{ decimal[,] j=new decimal[1,1];
decimal decimal1=0;
int s,S,c,C,K,M,i=0;
K=a.GetLength(1);
S=a.GetLength(0);
C=b.GetLength(1);
M=b.GetLength(0);
if((K!=1 || S!=1) && (C!=1 || M!=1) )
{
j=new decimal[S,C];
for(s=0;s<S;s++)
for(c=0;c<C;c++)
{ for(i=0;i<K;i++)
{decimal1+=a[s,i]*b[i,c];}
j[s,c]=decimal1;decimal1=0;
}
}
else if (K==1&&S==1)
{
j=new decimal[M,C];
for(int I=0;I<M;I++)
{
for(int J=0;J<C;J++)
j[I,J]=a[0,0]*b[I,J];
}
}
else if (C==1&&M==1)
{
j=new decimal[S,K];
for(int I=0;I<S;I++)
{
for(int J=0;J<K;J++)
j[I,J]=b[0,0]*a[I,J];
}
}
return j;
}
public static decimal[,] minuplate( decimal[,] a, decimal B)
{
int K=a.GetLength(1),S=a.Length/a.GetLength(1);
decimal[,] j=new decimal[S,K];
for(int i=0;i<S;i++)
{
for(int ii=0;ii<K;ii++)
{j[i,ii]=a[i,ii]*b; }
}
return j;
}
public static decimal[,] minuplate( decimal[,] a , decimal[,] b , decimal[,] c)
{
decimal[,] ab=minuplate(a,B);
decimal[,] abc=minuplate(ab,c);
return abc;
}
public static decimal[,] minuplate( decimal[,] a , decimal[,] b , decimal[,] c, decimal[,] d)
{ decimal[,] ab=minuplate(a,B);
decimal[,] abc=minuplate(ab,c);
decimal[,] abcd=minuplate(abc,d);
return abcd;
}
public static decimal sumOfMatrix(decimal[,] x)// مجموع عناصر مصفوفه
{
decimal sum=0;
foreach(decimal a in x)
{
sum+=a;
}
return sum;
}
public static decimal[,] SquarOfMatrix(decimal[,] x)// تربيع مصفوفه
{ decimal[,] xSquare=new decimal[x.GetLength(0),x.GetLength(1)];
for(int i=0;i<x.GetLength(0);i++)
{
for(int j=0;j<x.GetLength(1);j++)
{xSquare[i,j]=x[i,j]*x[i,j];
}
}
return xSquare;
}
public static decimal[,] Subtraction(decimal[,] a1,decimal[,] a2)//طرح المصفوفات
{decimal[,] answer=new decimal[a1.GetLength(0),a1.GetLength(1)];
for(int i=0;i<a1.GetLength(0);i++)
{ for(int j=0;j<a1.GetLength(1);j++)
{answer[i,j]=a1[i,j]-a2[i,j]; }
}
return answer;
}
public static decimal[,] Addition(decimal[,] a1,decimal[,] a2)//جمع المصفوفات
{ decimal[,] answer=new decimal[a1.GetLength(0),a1.GetLength(1)];
for(int i=0;i<a1.GetLength(0);i++)
{for(int j=0;j<a1.GetLength(1);j++)
{answer[i,j]=a1[i,j]+a2[i,j]; }
}
return answer;
}
}
التعامل مع الرجستري : Working With Registry
اولا قم بإضافة النيم سبيسس التالية :
كود
using Microsoft.Win32;
الأن بإمكانك الكتابة والقراءة من الرجستري كما يلي :
اولا للكتابة إلى الرجستري , حيث افترضنا ان اسم المفتاح هو FMO
كود
RegistryKey mykey = Registry.CurrentUser.CreateSubKey(@"Software\FMO");
mykey.SetValue("Fadi","اكتب هنا ما تريد لإضافته إلى الرجستري ");
mykey.Close ();
للقراءة من الرجستري , كما يلي:
كود
RegistryKey mykey = Registry.CurrentUser.CreateSubKey(@"Software\FMO");
MessageBox.Show (mykey.GetValue("Fadi").ToString ());
mykey.Close ();
تستطيع كذلك التغيير في بيئة النظام مثل اخفاء الساعة او قائمة ابدأ او غيرها كما يلي لإخفاء الساعة :
كود
RegistryKey mykey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer");
mykey.SetValue("HideClock",1);
mykey.Close ();
MessageBox.Show("You Should Make Restart to See The Chages!","Please",MessageBoxButtons.OK,MessageBoxIcon.Information);
وكما يلي لإرجاعها :
كود
RegistryKey mykey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer");
mykey.SetValue("HideClock",0);
mykey.Close ();
MessageBox.Show("You Should Make Restart to See The Chages!");
Operating System Info :
كود
ConnectionOptions co = new ConnectionOptions();
http://co.Username = "remoteUsername";//Only For Remote Machine
http://co.Password = "remotePassword";//Only For Remote Machine
//For Local Machine ( leave them )
string machineName = "localhost"; // or the IP of the remote machime
ManagementScope ms = new ManagementScope("\\\"+machineName+"\\root\\cimv2",co);
ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher mos = new ManagementObjectSearcher(ms,oq);
ManagementObjectCollection queryCollection = mos.Get();
foreach ( ManagementObject mo in queryCollection)
{
MessageBox.Show("Operating System: " + mo["Caption"]);
MessageBox.Show("Version: " + mo["Version"]);
MessageBox.Show("Manufacturer : " + mo["Manufacturer"]);
MessageBox.Show("Computer Name : " +mo["csname"]);
MessageBox.Show("Windows Directory : " + mo["WindowsDirectory"]);
MessageBox.Show("Serial Number : " + mo["SerialNumber"]);
}
Computer System Info:
كود
ConnectionOptions co = new ConnectionOptions();
http://co.Username = "remoteUsername";//Only For Remote Machine
http://co.Password = "remotePassword";//Only For Remote Machine
//For Local Machine ( leave them )
string machineName = "localhost"; // or the IP of the remote machime
ManagementScope ms = new ManagementScope("\\\"+machineName+"\\root\\cimv2",co);
ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_ComputerSystem");
ManagementObjectSearcher mos = new ManagementObjectSearcher(ms,oq);
ManagementObjectCollection queryCollection = mos.Get();
foreach ( ManagementObject mo in queryCollection)
{
MessageBox.Show("Computer Manufacturer Name: " + mo["Manufacturer"]);
MessageBox.Show("Computer Model: " + mo["model"]);
MessageBox.Show("System Type: " + mo["SystemType"]);
MessageBox.Show("Total Physical Memory: " + mo["totalphysicalmemory"]);
MessageBox.Show("Domain: " + mo["Domain"]);
MessageBox.Show("User Name: " + mo["UserName"]);
}
Processor Info
كود
ConnectionOptions co = new ConnectionOptions();
http://co.Username = "remoteUsername";//Only For Remote Machine
http://co.Password = "remotePassword";//Only For Remote Machine
//For Local Machine ( leave them )
string machineName = "localhost"; // or the IP of the remote machime
ManagementScope ms = new ManagementScope("\\\"+machineName+"\\root\\cimv2",co);
ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_processor");
ManagementObjectSearcher mos = new ManagementObjectSearcher(ms,oq);
ManagementObjectCollection queryCollection = mos.Get();
foreach ( ManagementObject mo in queryCollection)
{
MessageBox.Show("Manufacturer: " + mo["Manufacturer"]);
MessageBox.Show("Computer Processor: " + mo["Caption"]);
MessageBox.Show("CPU Speed: " + mo["MaxClockSpeed"]);
MessageBox.Show("L2 Cache Size: " + mo["L2CacheSize"]);
}
Bios Info
كود
ConnectionOptions co = new ConnectionOptions();
http://co.Username = "remoteUsername";//Only For Remote Machine
http://co.Password = "remotePassword";//Only For Remote Machine
//For Local Machine ( leave them )
string machineName = "localhost"; // or the IP of the remote machime
ManagementScope ms = new ManagementScope("\\\"+machineName+"\\root\\cimv2",co);
ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_bios");
ManagementObjectSearcher mos = new ManagementObjectSearcher(ms,oq);
ManagementObjectCollection queryCollection = mos.Get();
foreach ( ManagementObject mo in queryCollection)
{
MessageBox.Show("BIOS: " + mo["Caption"]);
MessageBox.Show("BIOS Version: " + mo["version"]);
}
Time Zone
كود
ConnectionOptions co = new ConnectionOptions();
http://co.Username = "remoteUsername";//Only For Remote Machine
http://co.Password = "remotePassword";//Only For Remote Machine
//For Local Machine ( leave them )
string machineName = "localhost"; // or the IP of the remote machime
ManagementScope ms = new ManagementScope("\\\"+machineName+"\\root\\cimv2",co);
ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_timezone");
ManagementObjectSearcher mos = new ManagementObjectSearcher(ms,oq);
ManagementObjectCollection queryCollection = mos.Get();
foreach ( ManagementObject mo in queryCollection)
{
MessageBox.Show("Time Zone: " + mo["Caption"]);
}
Memory Configuration
كود
ConnectionOptions co = new ConnectionOptions();
http://co.Username = "remoteUsername";//Only For Remote Machine
http://co.Password = "remotePassword";//Only For Remote Machine
//For Local Machine ( leave them )
string machineName = "localhost"; // or the IP of the remote machime
ManagementScope ms = new ManagementScope("\\\"+machineName+"\\root\\cimv2",co);
ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_LogicalMemoryConfiguration");
ManagementObjectSearcher mos = new ManagementObjectSearcher(ms,oq);
ManagementObjectCollection queryCollection = mos.Get();
foreach ( ManagementObject mo in queryCollection)
{
MessageBox.Show("Total Page File Space: " + mo["TotalPageFileSpace"]);
MessageBox.Show("Total Virtual Memory: "+mo["TotalVirtualMemory"]);
MessageBox.Show("Total Physical Memory: "+ mo["TotalPhysicalMemory"]);
}
Network Connection
كود
ConnectionOptions co = new ConnectionOptions();
http://co.Username = "remoteUsername";//Only For Remote Machine
http://co.Password = "remotePassword";//Only For Remote Machine
//For Local Machine ( leave them )
string machineName = "localhost"; // or the IP of the remote machime
ManagementScope ms = new ManagementScope("\\\"+machineName+"\\root\\cimv2",co);
ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_NetworkConnection");
ManagementObjectSearcher mos = new ManagementObjectSearcher(ms,oq);
ManagementObjectCollection queryCollection = mos.Get();
foreach ( ManagementObject mo in queryCollection)
{
MessageBox.Show("Name: " + mo["Name"]);
}
--------------------
Video Controller
كود
ConnectionOptions co = new ConnectionOptions();
http://co.Username = "remoteUsername";//Only For Remote Machine
http://co.Password = "remotePassword";//Only For Remote Machine
//For Local Machine ( leave them )
string machineName = "localhost"; // or the IP of the remote machime
ManagementScope ms = new ManagementScope("\\\"+machineName+"\\root\\cimv2",co);
ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_VideoController");
ManagementObjectSearcher mos = new ManagementObjectSearcher(ms,oq);
ManagementObjectCollection queryCollection = mos.Get();
foreach ( ManagementObject mo in queryCollection)
{
MessageBox.Show("Name: " + mo["Name"]);
MessageBox.Show("Processor: " + mo["VideoProcessor"]);
MessageBox.Show("Mode: " + mo["VideoModeDescription"]);
MessageBox.Show("Video Ram: " + mo["AdapterRAM"]);
MessageBox.Show("PNP Device ID: " + mo["PNPDeviceID"]);
MessageBox.Show("Status: " + mo["Status"]);
}
تقوم الميثود التالية بحساب الوقت المنقضي للتشغيل و ارجاع قيمة String تحتوي على الساعات و الدقائق ...
للبحث بين هذه الأكواد قم بضغط على المفتاحين
Control + F
----------------------------------------for loop & if condition
using System;
class Class1
{
public static void Main()
{
for (int i=0;i<5;i++){
if (i == 3) continue; // if (break mean end loop
Console.WriteLine (i);}
}
} /// the output is : 0 1 2 4
---------------------------------------------while loop:
using System;
class Class1
{
public static void Main()
{int i=0;
while (i<5){i++;
if (i == 3) continue;
Console.WriteLine (i);}
}
}/* -------> the out put is : 1245 */
---------------------------------------------do while loop:
using System;
class Class1
{
public static void Main()
{
int i=0;
do
{
i++;
if (i == 3) continue;
Console.WriteLine (i);
}
while (i<5);
}
}/* -------> the out put is : 1245 */
---------------------------------------------- foreach & Array
using System; // this program count the odd and even numbers within array :
class MainClass
{
public static void Main()
{
int odd = 0, even = 0;
int[] arr = new int [] {0,1,2,5,7,8,11};
foreach (int i in arr)
{
if (i%2 == 0)
even++;
else
odd++;
}
Console.WriteLine("Found {0} Odd Numbers, and {1} Even Numbers.",
odd, even);
}
} //The Output is :Found 4 Odd Numbers, and 3 Even Numbers.
----------------------------------------enum:
using System;
class Class1
{
enum color {red,green,blue}
public static void Main()
{
color c;
c=color.blue;
Console.WriteLine (c);
}
}
----------------------------------------- Working With Functions
- functions & functions call
- Access Modifier ( public , privit , protected )
- call static function and static class
-------------------------------functions & functions call EX:
using System;
class A
{
// Public Global Variable You Can Call This Variable From Any Class
public static int q=3;
static void Main()
{
//A y=new A(); //Creat y Object
//B z=new B(); // Creat z Object
http://z.xxx(); // Call Function xxx By Using z Object
Console.WriteLine (xxx ()+2); // function Call Without Object
}
// Use public to Allow Call This Function out main Class
// Use Static to Call Function Without Creat Object
public static int xxx()
{int z=10; return z;}
}
/*class B
{
public void xxx()
{A a=new A(); // Creat a Object
a.xxx(); // Call Function xxx By Using a Object
Console.WriteLine (a.q );} // Call Global Variable From Main Class
}*/
-----------------------------------------OOP :1-overload
وهي وجود اكثر من فنكشن تحمل نفس الأسم داخل الكلاس بحيث تختلف اما في الداتا تايب او في عدد الباراميترات
using System;
class a
{
static void Main()
{
C c=new C();
c.max(5,5);
c.max ('a','b');
}
public class d
{
public void yyy()
{
}
}
}
class b
{
void xxx()
{
a.d a=new a.d();
a.yyy ();
}
}
class C
{ // overload, tow functions have the same name
public int max(int x,int y)
{
if (x>y) return x; else return y;
}
public char max(char a,char b)
{
return a;
}
}
------------------------------------------------------- overload Ex:2
using System;
class A
{
static void Main()
{
int x=int.Parse (Console.ReadLine ());
int y=int.Parse (Console.ReadLine ());
Console.WriteLine (sum(x,y));
Console.WriteLine (sum(2.1f,2.5f));
}
static int sum(int x,int y)
{ return x+y; }
static float sum(float q,float w)
{return q+w;}
}
------------------------------------------------- boxing & Casting
كيفية تعريف اوبجكت وتحويلة الى اي نوع من الداتا تايب
using System;
class A
{
static void Main()
{
object o;
int y;
string s;
o=19;
y=(int) o;
o="main";
s=(string) o; Console.WriteLine (y + " " + s);
}
}
-------------------------------------------------OOP: 2-Inheritance
خاصية الوراثة مهمة جدا كونك تستطيع الوصول الى الميثودس الخاصة بكلاس الاب بدون الحاجة الى اعادة كتابة الكود مرة اخرى
using System;
class MC
{
static void Main()
{
A a=new A ();
B b=new B();
b.x=5;
b.y=3;
a.x=3;
}
}
class A
{
public A()
{
Console.WriteLine ("aaa");
}
public int x;
}
class B:A
{
public B()
{
Console.WriteLine ("bbb");
}
public int y;
}
-----------------------------------------------------interface Ex:1
using System;
class MC
{
static void Main()
{
A a=new A ();
B b=new B();
b.x=5;
b.y=3;
b.fun();
}
}
class A
{
public A()
{
Console.WriteLine ("aaa");
}
}
interface D
{
void fun();
}
class B:A,D
{
public B()
{
Console.WriteLine ("bbb");
}
public int y;
public int x;
public void fun()
{
Console.WriteLine ("Hello");
}
}
-----------------------------------------------interface EX:2
using System;
class MC
{
static void Main()
{
A a=new A ();
B b=new B();
b.x=5;
b.y=3;
b.fun();
b.fun2 ();
}
}
class A
{
public A()
{
Console.WriteLine ("aaa");
}
}
class B:A,D
{
public B()
{
Console.WriteLine ("bbb");
}
public int y;
public int x;
public void fun(){Console.WriteLine ("Hello Fun1");}
public void fun2(){Console.WriteLine ("Hello Fun2");}
}
interface D:F
{
void fun();
}
interface F
{
void fun2();
}
-----------------------------------------interface EX3:
using System;
class Class1
{
static void Main()
{
B b = new B();
b.xxx();
}
}
interface A
{
void xxx();
}
class B:A
{
public void xxx()
{
Console.WriteLine ("Hello");
}
}
-----------------------------// three interfaces inherited Ex4:
using System;
class Class1
{
static void Main()
{
B b = new B();
b.xxx1();
b.xxx2();
b.xxx3();
}
}
interface A
{
void xxx1();
}
interface AA:A
{
void xxx2();
}
interface AAA:AA
{
void xxx3();
}
class B:A
{
public void xxx1()
{Console.WriteLine ("Hello1");}
public void xxx2()
{Console.WriteLine ("Hello2");}
public void xxx3()
{Console.WriteLine ("Hello3");}
}
-------------------------------------------
نوع من الفنكشن لايمكن ان يورث
sealed -->this mean that class cannot be inheritened
Ex : sealed class a{ void main(){} }
------------------------------------------- abstract class
using System;
class MC
{
static void Main()
{
A a=new A ();
a.xxx (); // abstract class cannot get any object from it
} // if it was inherited or not
}
abstract class A // if we remove abstract word the program will run
{
public A()
{
}
public void xxx(){Console.WriteLine ("Hello");}
}
class B:A
{
public B()
{
}
} // The output here is Error msg Because we try to call function from abstract class
---------------------------------OOP :3-virtual function & override
يتم تنفيذ الفنكشن الأفتراضية في حالة عدم تطابق شروط الاوفر رايد
using System;
class MC
{
static void Main()
{
A a=new B (); // creat a object from A class that has the size of B clss
a.xxx(); // call virtual function or override function if existing
}
}
class A
{
public A() // Construct Function
{
}
public virtual void xxx() // Virtual Function Called in this Examble if no found override function
{ Console.WriteLine ("aaa");}
}
class B:A // Class B Inherited from A Class
{
public B() // Construct Function
{
}
public override void xxx()// override function that called in this //Examble
{Console.WriteLine ("bbb");}
}
-----------------------------------------------------Refrance
تبقى قيمة المتغير محفوظة في الذاكرة حتى بعد تنفيذ الفنكشن
using System;
class MC
{
static void Main()
{
int y=3;
MC m=new MC ();
m.xxx (ref y); // call 1 x=x+1
m.xxx (ref y);// call 2 x=x+1
m.xxx (ref y);// call 3 x=x+1
}
public void xxx(ref int x) // ref mean save the value of x when exit from fuction
{ x++; Console.WriteLine (x);}
// the output with ref is: 4 5 6
// the output without ref is: 4 4 4
}
--------------------------------------------------- out
using System;
class MC
{
static void Main()
{
int y;
MC m=new MC ();
m.xxx (out y); // print the value of y from variable x
// use out to Allow Compiler to installaize the variable in other function
}
public void xxx(out int x)
{ x=3; Console.WriteLine (x);}
}
--------------------------------------------------- params
using System;
class MC
{
static void Main()
{
MC m=new MC ();
m.xxx (10,20,30); // insert more then value in function that has one Parameter
}
public void xxx(params int[] x) // insert the values in Array
{
int z=0;
for (int i=0; i<x.Length; i++)
z=z+x[i];
Console.WriteLine (z);}}
-------------------------------------------------Args :
يمكن الأستفادة منها في حالة اذا اردنا اتباع اوامر اخرى بعد كتابة اسم الملف الذي نريد تنفيذه
using System;
class MC
{
static void Main(string [] args)
{
int q=0;
if (args.Length >0)
{
for (int i=0;i<args.Length;i++)
{
int z=int.Parse (args[i]);
q+=z;
}
Console.WriteLine (q);
}
else Console.WriteLine ("no input");
}
}
-------------------------------------------------Exception :
تستخدم الاستثنائات لسيطرة على الاخطاء التي يمكن ان تحدث اثناء تنفيذ الكود
using System; //Examble 1
class MC
{
static void Main()
{
int x,y,z;
x= int.Parse ( Console.ReadLine ());
y= int.Parse ( Console.ReadLine ());
try
{
z=x/y;
}
catch (Exception)
{
Console.WriteLine ("Error1");
}
}
}
----------------------------------------------------
using System; //Examble 2
class MC
{
static void Main()
{
int x,y,z;
x= int.Parse ( Console.ReadLine ());
y= int.Parse ( Console.ReadLine ());
try
{
z=x/y;
}
catch (Exception e)
{
Console.WriteLine (e.Message);
}
}
}
--------------------------------------------------
using System; //Examble 3
class MC
{
static void Main()
{
int x,y,z;
x= int.Parse ( Console.ReadLine ());
y= int.Parse ( Console.ReadLine ());
try
{
z=x/y;
}
catch (DivideByZeroException)
{
Console.WriteLine ("Error1");
}
catch (Exception e)
{
Console.WriteLine (e.Message);
}
finally
{
Console.WriteLine ("Error finally");
}
}
}
--------------------------------------------checked overflow
using System;
class MC
{
static void Main()
{
int x,y,z;
try
{
checked
{ z=int.MaxValue;
Console.WriteLine (z);
z++;
Console.WriteLine (z);}
}
catch (Exception e)
{
Console.WriteLine (e.Message); } } }
--------------------------------------------string
using System;
class MC
{
static void Main()
{
string a="main jitawi";
char f1= a[2];
Console.WriteLine(f1);
string b="c is great";
string b2=b.Insert(2,"sharp");
Console.WriteLine(b2);
string msg="hello";
int c=msg.Length;
Console.WriteLine(c);
string d="hello";
string d2=string.Copy (d);
Console.WriteLine(d2);
string e=string.Concat ("a","b","c","d");
Console.WriteLine(e);
string e2=string.Concat ("a"+"b"+"c"+"d");
Console.WriteLine(e2);
string e3 = "a"+"b"+"c"+"d";
Console.WriteLine(e3);
}
}
---------------------------------------------Refliction
using System; // use this program to know info about string methods
using System.Reflection;
class MC
{
static void Main()
{
Type t=typeof(byte);
Console.WriteLine("Type:{0}",t);
Type t1=typeof(string);
MethodInfo [] mi=t1.GetMethods();
foreach (MethodInfo m in mi)
{ Console.WriteLine("Method:{0}",m);}
}}
--------------------------------------------------File
القرائة و الكتابة على ملف تكست
using System;// get strings from Text File
using System.IO; // and write Strings on Text File
class A
{
static void Main()
{
StreamReader reder = new StreamReader("c:\\ali1.txt");
StreamWriter writer = new StreamWriter("c:\\ali2.txt");
string line;
while((line = reder.ReadLine())!=null)
{writer.WriteLine(line);}
reder.Close();
writer.Close();
}
}
-----------------------------------------namespace
التعامل مع النيم سبيس
using System;
namespace xxx
{
class A
{
static void Main()
{
yyy.zzz.B b=new yyy.zzz.B ();
b.fun ();
}
}
}
namespace yyy
{
namespace zzz
{
class B
{
public void fun(){Console.WriteLine("Hello");}
}
}}
-------------------------------------------unsafe code
استخدام البوينترز في السي شارب
using System;// Allow to useing pointers with C#
namespace xxx
{
class A
{
static void Main()
{
yyy.zzz.B b=new yyy.zzz.B ();
b.fun ();
}
}
}
namespace yyy
{
namespace zzz
{
class B
{
unsafe public void fun(){int a=5;int *p=&a;Console.WriteLine(*p);}
}
}}
---------------------------------------------Proparity Ex:1
كيفية عمل بروبرتي في السي شارب
using System;
class A
{
static void Main()
{
B b = new B();
b.fun();
Console.WriteLine (x);
}
static private int x;
public void set_xxx(int i) {x=i;}
}
class B
{
public void fun()
{
A a=new A();
a.set_xxx (5);
}}
----------------------------------------------------Proparity Ex:2
using System;
class A
{
static void Main()
{
B b = new B();
b.fun();
}
static private int x;
public void set_xxx(int i) {x=i;}
public int get_xxx(){return x;}
}
class B
{
public void fun()
{
A a=new A();
a.set_xxx (5);
Console.WriteLine (a.get_xxx());
}
}
-----------------------------------------------Proparity Ex:3
using System;
class A
{
static void Main()
{
B b = new B();
b.fun();
}
private int name;
public int Name{ set{name=value;} get{return name;}
}
}
class B
{
public void fun()
{
A a=new A();
a.Name=5;
Console.WriteLine (a.Name);
}}
-------------------------------------------------delegate
using System;
class A
{
public delegate void qq();
static void Main()
{
qq q=new qq (xxx);
q();
q=new qq (yyy);
q();
q=new qq (zzz);
q();
}
public static void xxx(){Console.WriteLine ("xxxxxx");}
public static void yyy(){Console.WriteLine ("yyyyyy");}
public static void zzz(){Console.WriteLine ("zzzzzz");}
}
----------------------------------------------- Delegate Ex:2
using System;
class A
{
public delegate void xxx(int a,int b);
static void Main()
{
xxx q=new xxx (fun2);
q(2,12);
A a =new A ();
q = new xxx (a.fun1 );
q(3,4);
D d=new D();
q= new xxx (d.fun3 );
q(8,9);
}
public void fun1(int x,int y)
{int z;z=x+y;Console.WriteLine (z);}
public static void fun2(int x,int y)
{int z;z=x*y;Console.WriteLine (z);}
}
class D
{
public void fun3(int x,int y)
{Console.WriteLine (x);}}
--------------------------------------------------------event
using System;
public delegate void A();
class B
{
public event A C;// declaration event C
public void D() {C();}
}
public class E
{
static private void f(){ Console.WriteLine ("Hello");}
static public void x() {Console.WriteLine ("Hello2");}
static void Main()
{
B b=new B ();
b.C +=new A;// store the output of function f in event C
b.C +=new A(x);// store the output of function x in event C
b.D ();//call D function to Veiw the event stores
}
}
----------------------------------------------------------this
/*call any External object function or variable from the same class without make object to call it,cannot uses with static functions or static variables ,can be used to access members from within constructors.*/
using System;
public class A
{
int x=34;
public static void Main()
{
A a=new A ();
a.fun ();
}
public void fun()
{
Console.WriteLine (this.x );
}
}
----------------------------------------------------------index
using System;
class BookIndexor
{
private int [] bookcollection = new int [50];
//b[3]
public int this [int index]
{
get
{
if (index<0||index>=50) return 0;
else return bookcollection[index];
}
set
{if (!(index<0||index>=50))bookcollection[index]=value;}
} //3 256
}
public class MainClass
{
public static void Main()
{
BookIndexor b=new BookIndexor ();
b[3]=256;
for (int i=0;i<=3;i++)
{
Console.WriteLine ("Book Collection #{0}={1}",i,b[i]);
}
}
}
------------------------------------------------------------------------------------------------------------
التعامل مع قواعد البيانات
using System; ADO.NET Consol Example
using System.Data;
using System.Data.OleDb;
namespace ADODotNet
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
OleDbConnection myConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;DataSource=Test.MDB");
// open connection
myConnection.Open();
//to Create DataAdapter object for upadte or other operation
OleDbDataAdapter myAdapter=new OleDbDataAdapter("SELECT * FROM Table1",myConnection);
OleDbCommandBuilder myBuild=new leDbCommandBuilder(myAdapter);
//to Create DataSet to contain related data tables,rows and columns
DataSet myDataSet=new DataSet();
//to Fill DataSet from Table1
myAdapter.Fill(myDataSet,"Table1");
/*set up keys object for defining primary key
*Before you using find we have to set up a primary you'll use during searching */
DataColumn[] keys=new DataColumn[1];
keys[0]=myDataSet.Tables["Table1"].Columns["Column1"];
myDataSet.Tables["Table1"].PrimaryKey=keys;
DataRow findRow=myDataSet.Tables["Table1"].Rows.Find("mazy");
if(findRow==null)
{
Console.WriteLine("mazy,not found and I'll add it to table");
DataRow myRow=myDataSet.Tables["Table1"].NewRow();
myRow["Column1"]="mazy";
myRow["Column2"]="Hello everybody!";
myDataSet.Tables["Table1"].Rows.Add(myRow);
if((findRow=myDataSet.Tables["Table1"]
.Rows.Find("mazy"))!=null)
Console.WriteLine("mazy,successfully added to Table1");
}
Else
{
Console.WriteLine("mazy,already present in database");
}
myAdapter.Update(myDataSet,"Table1");
myConnection.Close();
}}}
-------------------------------------------------------------------
برنامج شات مبسط بستخدام الكونسول
using System; Socket Example – Server Code
using System.Text;
using System.Net;
using System.Net.Sockets;
public class serv
{
public static void Main()
{
Console.WriteLine("Finding Client...");
xxx:
try
{
IPAddress ipAd = IPAddress.Parse("192.168.0.2"); //use local m/c IP adds, and use the same in the client
TcpListener myList=new TcpListener(ipAd,8001);
myList.Start();
Socket s=myList.AcceptSocket();
Console.Write("Message From " + ipAd + ": ");
byte[] b=new byte[100];
int k=s.Receive(b);
for (int i=0;i<k;i++)
Console.Write(Convert.ToChar(b[i]));
Console.WriteLine ("");
ASCIIEncoding asen=new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
s.Close();
myList.Stop();
goto xxx;
}
catch (Exception)
{
goto xxx;
}
}
}
using System; Socket Example – Client Code
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
public class clnt
{
public static void Main()
{
Console.Write("Connecting.....");
xxx:
try
{
TcpClient tcpclnt = new TcpClient();
Console.Write(".");
tcpclnt.Connect("192.168.0.2",8001); // use the ipaddress as in the server program
Console.WriteLine("Connected");
Console.Write("Enter Your Message : ");
String str=Console.ReadLine();
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen= new ASCIIEncoding();
byte[] ba=asen.GetBytes(str);
Console.WriteLine("Transmitting.....");
stm.Write(ba,0,ba.Length);
byte[] bb=new byte[100];
int k=stm.Read(bb,0,100);
for (int i=0;i<k;i++)
Console.Write(Convert.ToChar(bb[i]));
if (str=="end") tcpclnt.Close();
else
goto xxx;
}
catch (Exception)
{
goto xxx;
}
}
}
التعامل مع ال Controls في ال Windows Applications
كود
Rich Text Box
// to set rich text box fill on the form
richTextBox2.Dock = DockStyle.Fill;
// to load file from drive C:\ into buffer by using rich text box
richTextBox2.LoadFile("C:\\mmm.rtf");
// to load file from any path
FileDialog ff;
ff=new OpenFileDialog();
ff.ShowDialog();
string ss=ff.FileName.ToString();
richTextBox2.LoadFile(ss);
// to change the text font at the rich text box
richTextBox2.Font = new Font("Verdana", 12, FontStyle.Italic);
//to change the text color at the rich text box
richTextBox2.ForeColor = Color.Red;
// to display the content of the buffer into rich text box
Controls.Add(richTextBox2);
// to save the content of rich text box into file at drive C:\
richTextBox2.SaveFile("C:\\MyDocument.rtf",RichTextBoxStreamType.RichText);
// to save as by setting file name , file type and its path
FileDialog ff;
ff=new SaveFileDialog();
ff.ShowDialog();
string ss=ff.FileName.ToString();
richTextBox2.SaveFile(ss, RichTextBoxStreamType.RichText);
//to perform searching to find any word occurs at the rich text box
richTextBox2.Find(textBox1.Text, RichTextBoxFinds.MatchCase);
//to change the font of the selection word
richTextBox2.SelectionFont = new Font("Verdana", 12, FontStyle.Bold);
//to change the font color of the selection word
richTextBox2.SelectionColor = Color.Blue;
//to clear all the content of the rich text box
richTextBox2.ResetText();
//to select all the content of the rich text box
richTextBox2.SelectAll();
//to make hyper link with internet we must insert LinkClicked rich text box handler into your project
private void richTextBox2_LinkClicked(object sender,System.Windows.Forms.LinkClickedEventArgs e)
{
System.Diagnostics.Process.Start(e.LinkText);
}
//and the system construct the following object through constructor call.
this.richTextBox2.LinkClicked += new System.Windows.Forms.LinkClickedEventHandler(this.richTextBox2_LinkClicked);
// we use menu item with the check property, if it is checked previously or not then we change it into un checked and set text attribute at the rich text box into read only else we change it into checked and set text read and write
if(menuItem8.Checked) {
menuItem8.Checked=false;
richTextBox2.ReadOnly= false;
}
else {
menuItem8.Checked=true;
richTextBox2.ReadOnly= true;
}
Radio and Check Box
//we use sender obj to check if we select radio button 1 or radio button 2
private void radioButton1_CheckedChanged(object sender, System.EventArgs e)
{
if(sender == radioButton1)
xx=0;
else if(sender == radioButton2)
xx=1;
}
// we call checked property by the radio button object and check its value if it is true or false. This process is used to fix which radio control is selected
private void radioButton3_Click(object sender, System.EventArgs e)
{
if(radioButton3.Checked)
MessageBox.Show("r3");
else if(radioButton4.Checked)
MessageBox.Show("r4");
}
// call checked by the check box object and show if we checked or not
private void checkBox1_CheckedChanged(object sender, System.EventArgs e)
{
if(checkBox1.Checked)
MessageBox.Show("hhhh");
}
ListBox & ComboBox
// To assign selected text value from combo or list box to text box control
textBox1.Text=comboBox2.Text;
textBox1.Text=listBox1.Text;
//To add an item to a list or combo box control
listBox1.Items.Add(textBox1.Text);
comboBox1.Items.Add(textBox1.Text);
//To remove an item from a list or combo box control
listBox1.Items.Remove(textBox1.Text);
comboBox1.Items.Remove(textBox1.Text);
//To remove an item at the 3rd location of the list or combo box control
listBox1.Items.RemoveAt(2);
comboBox1.Items.RemoveAt(2);
//To insert an item at the 4th location of the list or combo box
listBox1.Items.Insert(3,"NAMEER");
comboBox1.Items.Insert(3,"NAMEER");
Painter and Mouse Events
// Using window message Mouse Event Handling (MouseDown button) to set mouse location by the object e of the MouseEvent class and set true to the paint status
private void Painter_MouseDown(object sender,System.Windows.Forms.MouseEventArgs e )
{
xx=e.X;
yy=e.Y;
shouldPaint = true; //paint status
}
// Using window message Mouse Event Handling (MouseUp button) to set false to paint status
private void Painter_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e )
{
shouldPaint = false;
}
// using window message Mouse Event Handling (MouseMove), if the paint status is true then perform painting else not paint
protected void Painter_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
if ( shouldPaint ) {
Pen p=new Pen(Color.Black); // set pen style and pen color
Graphics g = CreateGraphics(); // create graphics object to call graphical //function
SolidBrush sb=new SolidBrush(Color.Red); // set brush color
/*either */ g.FillEllipse(new SolidBrush( Color.Red) ,e.X, e.Y,10, 10);
/* Or */ g.FillEllipse(sb ,e.X, e.Y,150, 150);
g.FillRectangle(sb ,e.X, e.Y,150, 150);
g.DrawLine(p,xx,yy,e.X,e.Y);
xx=e.X;
yy=e.Y;
g.DrawEllipse(p,e.X,e.Y,150,115);
g.DrawPie(p,e.X,e.Y,50,50,0,360); // (pen,e.X,e.Y,starting point(50,50),from angle = 0 to angle =360)
g.DrawRectangle(p,e.X,e.Y,150,115);
}
}
Build Button&TextBox at RunTime
// declared two objects from types TextBox and Button respectively
private System.Windows.Forms.TextBox myTextBox;
private System.Windows.Forms.Button button2;
//create at a runtime new textbox and new button when we click button 5
private void button5_Click(object sender, System.EventArgs e)
{
myTextBox = new TextBox();
myTextBox.Location = new Point (30, 20); // set position of myTextBox
Controls.Add (myTextBox); // Put the myTextBox on the form.
button2 = new Button();
button2.Location = new Point (100, 100); //set position of button2
button2.Size = new System.Drawing.Size(100, 100); // set the size
Controls.Add (button2); // Put the button2 on the form.
button2.Text="ADD";// set label on button2
button2.Click += new EventHandler(button2_Click); //create EventHandler to the button2
}
// Apply window message MouseUp and using event handler object e to check which mouse button is clicked up
private void Form1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
// Show is a static method of System.Windows.Forms.MessageBox
MessageBox.Show ("Right up Click!");
if (e.Button == MouseButtons.Left)
// Show is a static method of System.Windows.Forms.MessageBox
MessageBox.Show ("Left up Click!");
}
Timer
private System.Windows.Forms.Timer timer1;
//changing timer property at the runtime
private void button1_Click(object sender, System.EventArgs e)
{
timer1 = new Timer(); //Create Timer Object
timer1.Interval = 1000; // set one second time interval
timer1.Enabled = true; // to start timer
}
// Or using start function under setting of the timer properties
private void button1_Click(object sender, System.EventArgs e)
{ timer1.Start();
timer1.Tick += new EventHandler (timer1_Tick); // call function for each second according to interval property setting
Using Stop() function
private void button2_Click(object sender, System.EventArgs e)
{
timer1.Stop();
}
TextBox and Font properties
private void menuItem2_Click(object sender, System.EventArgs e)
{
int x=int.Parse(textBox1.Text);
x+=10;
textBox1.Text=x.ToString();
}
private void button1_Click(object sender, System.EventArgs e){
http://textBox1.Font=new Font(textBox1.Font.Name, textBox1.Font.Size ,textBox1.Font.Style ^ FontStyle.Italic);
textBox1.Font=new Font("Arial",14,FontStyle.Bold);
FontConverter.FontNameConverter
ColorDialog cc=new ColorDialog();
cc.ShowDialog();
textBox1.ForeColor=cc.Color;
textBox2.Visible=false;
}
private void button2_Click(object sender, System.EventArgs e)
{
textBox1.Font=new Font("Comic Sans MS",36,FontStyle.Bold);
textBox1.Clear();
textBox1.Focus();
textBox1.AppendText("NAMEER");
FontDialog b=new FontDialog();
b.ShowDialog();
textBox1.Font=b.Font;
ColorDialog cc=new ColorDialog();
cc.ShowDialog();
textBox1.ForeColor=cc.Color;
http://textBox1.BackColor=Color.Red;//Color.DarkRed;
http://textBox1.ForeColor=Color.Blue;
textBox1.TextAlign=HorizontalAlignment.Right;
int n= textBox2.Text.Length;
textBox3.Text=n.ToString();
}
private void button3_Click(object sender, System.EventArgs e)
{
button1.Text="ADD";
ColorDialog cc=new ColorDialog();
cc.ShowDialog();
button1.ForeColor=cc.Color;
FontDialog b=new FontDialog();
b.ShowDialog();
button1.Font=b.Font;
if(button1.Text=="ADD")
button2.Text="MUL";
button1.Enabled=false;
}
private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
// Show is a static method of System.Windows.Forms.MessageBox
MessageBox.Show ("Right Click!");
}
private void gg_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
// Show is a static method of System.Windows.Forms.MessageBox
MessageBox.Show ("Left Click!");
}
Check List Box
Set selection item into item variable, and check if your action is checked or not if yes, set item into list box else remove item from list box.
private void inputCheckedListBox_ItemCheck(object sender, System.Windows.Forms.ItemCheckEventArgs e)
{
string item = inputCheckedListBox.SelectedItem.ToString();
// if(e.NewValue==CheckState.Checked)
/* or using */ if(e.NewValue.ToString()=="Checked")
displayListBox.Items.Add( item );
else
displayListBox.Items.Remove( item );
}
Using SelectedIndexChanged event handling to perform operations on the checkedListBox control.
private void checkedListBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
string item=checkedListBox1.SelectedItem.ToString();
if(checkedListBox1.CheckedItems.ToString()=="ADD")
{
int n=int.Parse(textBox1.Text)+int.Parse(textBox2.Text);
textBox1.Text=n.ToString();
}
if(checkedListBox1.CheckedItems.ToString()=="MUL")
{
int n=int.Parse(textBox1.Text)*int.Parse(textBox2.Text);
textBox1.Text=n.ToString();
}
}
لتشغيل ملف صوت في السي شارب قم بإضافة ما يلي :
Play Wave Sound
اولا :
كود
using System.Runtime.InteropServices;
ثانيا نعرف دالة كالأتي :
كود
[DllImport("winmm.dll")]
private static extern int PlaySoundA(string a,int b , int c);
ثالثا نستدعي الدالة في زر أمر كالتالي :
كود
PlaySoundA(@"file name here",0,0);
مجموعة اكواد لتعامل مع المصفوفات - Array
كود
public class Matrices
{
public static decimal[,] minuplate( decimal[,] a, decimal[,] B)// ضرب المصفوفات
{ decimal[,] j=new decimal[1,1];
decimal decimal1=0;
int s,S,c,C,K,M,i=0;
K=a.GetLength(1);
S=a.GetLength(0);
C=b.GetLength(1);
M=b.GetLength(0);
if((K!=1 || S!=1) && (C!=1 || M!=1) )
{
j=new decimal[S,C];
for(s=0;s<S;s++)
for(c=0;c<C;c++)
{ for(i=0;i<K;i++)
{decimal1+=a[s,i]*b[i,c];}
j[s,c]=decimal1;decimal1=0;
}
}
else if (K==1&&S==1)
{
j=new decimal[M,C];
for(int I=0;I<M;I++)
{
for(int J=0;J<C;J++)
j[I,J]=a[0,0]*b[I,J];
}
}
else if (C==1&&M==1)
{
j=new decimal[S,K];
for(int I=0;I<S;I++)
{
for(int J=0;J<K;J++)
j[I,J]=b[0,0]*a[I,J];
}
}
return j;
}
public static decimal[,] minuplate( decimal[,] a, decimal B)
{
int K=a.GetLength(1),S=a.Length/a.GetLength(1);
decimal[,] j=new decimal[S,K];
for(int i=0;i<S;i++)
{
for(int ii=0;ii<K;ii++)
{j[i,ii]=a[i,ii]*b; }
}
return j;
}
public static decimal[,] minuplate( decimal[,] a , decimal[,] b , decimal[,] c)
{
decimal[,] ab=minuplate(a,B);
decimal[,] abc=minuplate(ab,c);
return abc;
}
public static decimal[,] minuplate( decimal[,] a , decimal[,] b , decimal[,] c, decimal[,] d)
{ decimal[,] ab=minuplate(a,B);
decimal[,] abc=minuplate(ab,c);
decimal[,] abcd=minuplate(abc,d);
return abcd;
}
public static decimal sumOfMatrix(decimal[,] x)// مجموع عناصر مصفوفه
{
decimal sum=0;
foreach(decimal a in x)
{
sum+=a;
}
return sum;
}
public static decimal[,] SquarOfMatrix(decimal[,] x)// تربيع مصفوفه
{ decimal[,] xSquare=new decimal[x.GetLength(0),x.GetLength(1)];
for(int i=0;i<x.GetLength(0);i++)
{
for(int j=0;j<x.GetLength(1);j++)
{xSquare[i,j]=x[i,j]*x[i,j];
}
}
return xSquare;
}
public static decimal[,] Subtraction(decimal[,] a1,decimal[,] a2)//طرح المصفوفات
{decimal[,] answer=new decimal[a1.GetLength(0),a1.GetLength(1)];
for(int i=0;i<a1.GetLength(0);i++)
{ for(int j=0;j<a1.GetLength(1);j++)
{answer[i,j]=a1[i,j]-a2[i,j]; }
}
return answer;
}
public static decimal[,] Addition(decimal[,] a1,decimal[,] a2)//جمع المصفوفات
{ decimal[,] answer=new decimal[a1.GetLength(0),a1.GetLength(1)];
for(int i=0;i<a1.GetLength(0);i++)
{for(int j=0;j<a1.GetLength(1);j++)
{answer[i,j]=a1[i,j]+a2[i,j]; }
}
return answer;
}
}
التعامل مع الرجستري : Working With Registry
اولا قم بإضافة النيم سبيسس التالية :
كود
using Microsoft.Win32;
الأن بإمكانك الكتابة والقراءة من الرجستري كما يلي :
اولا للكتابة إلى الرجستري , حيث افترضنا ان اسم المفتاح هو FMO
كود
RegistryKey mykey = Registry.CurrentUser.CreateSubKey(@"Software\FMO");
mykey.SetValue("Fadi","اكتب هنا ما تريد لإضافته إلى الرجستري ");
mykey.Close ();
للقراءة من الرجستري , كما يلي:
كود
RegistryKey mykey = Registry.CurrentUser.CreateSubKey(@"Software\FMO");
MessageBox.Show (mykey.GetValue("Fadi").ToString ());
mykey.Close ();
تستطيع كذلك التغيير في بيئة النظام مثل اخفاء الساعة او قائمة ابدأ او غيرها كما يلي لإخفاء الساعة :
كود
RegistryKey mykey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer");
mykey.SetValue("HideClock",1);
mykey.Close ();
MessageBox.Show("You Should Make Restart to See The Chages!","Please",MessageBoxButtons.OK,MessageBoxIcon.Information);
وكما يلي لإرجاعها :
كود
RegistryKey mykey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer");
mykey.SetValue("HideClock",0);
mykey.Close ();
MessageBox.Show("You Should Make Restart to See The Chages!");
Operating System Info :
كود
ConnectionOptions co = new ConnectionOptions();
http://co.Username = "remoteUsername";//Only For Remote Machine
http://co.Password = "remotePassword";//Only For Remote Machine
//For Local Machine ( leave them )
string machineName = "localhost"; // or the IP of the remote machime
ManagementScope ms = new ManagementScope("\\\"+machineName+"\\root\\cimv2",co);
ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher mos = new ManagementObjectSearcher(ms,oq);
ManagementObjectCollection queryCollection = mos.Get();
foreach ( ManagementObject mo in queryCollection)
{
MessageBox.Show("Operating System: " + mo["Caption"]);
MessageBox.Show("Version: " + mo["Version"]);
MessageBox.Show("Manufacturer : " + mo["Manufacturer"]);
MessageBox.Show("Computer Name : " +mo["csname"]);
MessageBox.Show("Windows Directory : " + mo["WindowsDirectory"]);
MessageBox.Show("Serial Number : " + mo["SerialNumber"]);
}
Computer System Info:
كود
ConnectionOptions co = new ConnectionOptions();
http://co.Username = "remoteUsername";//Only For Remote Machine
http://co.Password = "remotePassword";//Only For Remote Machine
//For Local Machine ( leave them )
string machineName = "localhost"; // or the IP of the remote machime
ManagementScope ms = new ManagementScope("\\\"+machineName+"\\root\\cimv2",co);
ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_ComputerSystem");
ManagementObjectSearcher mos = new ManagementObjectSearcher(ms,oq);
ManagementObjectCollection queryCollection = mos.Get();
foreach ( ManagementObject mo in queryCollection)
{
MessageBox.Show("Computer Manufacturer Name: " + mo["Manufacturer"]);
MessageBox.Show("Computer Model: " + mo["model"]);
MessageBox.Show("System Type: " + mo["SystemType"]);
MessageBox.Show("Total Physical Memory: " + mo["totalphysicalmemory"]);
MessageBox.Show("Domain: " + mo["Domain"]);
MessageBox.Show("User Name: " + mo["UserName"]);
}
Processor Info
كود
ConnectionOptions co = new ConnectionOptions();
http://co.Username = "remoteUsername";//Only For Remote Machine
http://co.Password = "remotePassword";//Only For Remote Machine
//For Local Machine ( leave them )
string machineName = "localhost"; // or the IP of the remote machime
ManagementScope ms = new ManagementScope("\\\"+machineName+"\\root\\cimv2",co);
ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_processor");
ManagementObjectSearcher mos = new ManagementObjectSearcher(ms,oq);
ManagementObjectCollection queryCollection = mos.Get();
foreach ( ManagementObject mo in queryCollection)
{
MessageBox.Show("Manufacturer: " + mo["Manufacturer"]);
MessageBox.Show("Computer Processor: " + mo["Caption"]);
MessageBox.Show("CPU Speed: " + mo["MaxClockSpeed"]);
MessageBox.Show("L2 Cache Size: " + mo["L2CacheSize"]);
}
Bios Info
كود
ConnectionOptions co = new ConnectionOptions();
http://co.Username = "remoteUsername";//Only For Remote Machine
http://co.Password = "remotePassword";//Only For Remote Machine
//For Local Machine ( leave them )
string machineName = "localhost"; // or the IP of the remote machime
ManagementScope ms = new ManagementScope("\\\"+machineName+"\\root\\cimv2",co);
ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_bios");
ManagementObjectSearcher mos = new ManagementObjectSearcher(ms,oq);
ManagementObjectCollection queryCollection = mos.Get();
foreach ( ManagementObject mo in queryCollection)
{
MessageBox.Show("BIOS: " + mo["Caption"]);
MessageBox.Show("BIOS Version: " + mo["version"]);
}
Time Zone
كود
ConnectionOptions co = new ConnectionOptions();
http://co.Username = "remoteUsername";//Only For Remote Machine
http://co.Password = "remotePassword";//Only For Remote Machine
//For Local Machine ( leave them )
string machineName = "localhost"; // or the IP of the remote machime
ManagementScope ms = new ManagementScope("\\\"+machineName+"\\root\\cimv2",co);
ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_timezone");
ManagementObjectSearcher mos = new ManagementObjectSearcher(ms,oq);
ManagementObjectCollection queryCollection = mos.Get();
foreach ( ManagementObject mo in queryCollection)
{
MessageBox.Show("Time Zone: " + mo["Caption"]);
}
Memory Configuration
كود
ConnectionOptions co = new ConnectionOptions();
http://co.Username = "remoteUsername";//Only For Remote Machine
http://co.Password = "remotePassword";//Only For Remote Machine
//For Local Machine ( leave them )
string machineName = "localhost"; // or the IP of the remote machime
ManagementScope ms = new ManagementScope("\\\"+machineName+"\\root\\cimv2",co);
ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_LogicalMemoryConfiguration");
ManagementObjectSearcher mos = new ManagementObjectSearcher(ms,oq);
ManagementObjectCollection queryCollection = mos.Get();
foreach ( ManagementObject mo in queryCollection)
{
MessageBox.Show("Total Page File Space: " + mo["TotalPageFileSpace"]);
MessageBox.Show("Total Virtual Memory: "+mo["TotalVirtualMemory"]);
MessageBox.Show("Total Physical Memory: "+ mo["TotalPhysicalMemory"]);
}
Network Connection
كود
ConnectionOptions co = new ConnectionOptions();
http://co.Username = "remoteUsername";//Only For Remote Machine
http://co.Password = "remotePassword";//Only For Remote Machine
//For Local Machine ( leave them )
string machineName = "localhost"; // or the IP of the remote machime
ManagementScope ms = new ManagementScope("\\\"+machineName+"\\root\\cimv2",co);
ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_NetworkConnection");
ManagementObjectSearcher mos = new ManagementObjectSearcher(ms,oq);
ManagementObjectCollection queryCollection = mos.Get();
foreach ( ManagementObject mo in queryCollection)
{
MessageBox.Show("Name: " + mo["Name"]);
}
--------------------
Video Controller
كود
ConnectionOptions co = new ConnectionOptions();
http://co.Username = "remoteUsername";//Only For Remote Machine
http://co.Password = "remotePassword";//Only For Remote Machine
//For Local Machine ( leave them )
string machineName = "localhost"; // or the IP of the remote machime
ManagementScope ms = new ManagementScope("\\\"+machineName+"\\root\\cimv2",co);
ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_VideoController");
ManagementObjectSearcher mos = new ManagementObjectSearcher(ms,oq);
ManagementObjectCollection queryCollection = mos.Get();
foreach ( ManagementObject mo in queryCollection)
{
MessageBox.Show("Name: " + mo["Name"]);
MessageBox.Show("Processor: " + mo["VideoProcessor"]);
MessageBox.Show("Mode: " + mo["VideoModeDescription"]);
MessageBox.Show("Video Ram: " + mo["AdapterRAM"]);
MessageBox.Show("PNP Device ID: " + mo["PNPDeviceID"]);
MessageBox.Show("Status: " + mo["Status"]);
}
الثلاثاء مارس 13, 2012 3:39 pm من طرف Admin
» An Introduction to VBA in Excel
السبت مارس 10, 2012 1:03 pm من طرف Admin
» المهرجان الخيرى الثالث لجمعية مصريين
الخميس مارس 08, 2012 1:47 pm من طرف Admin
» هندسة الشبكات
الأربعاء مارس 07, 2012 7:59 pm من طرف Admin
» ﺎﻬﺗﺎﻘﻴﺒﻄﺗﻭ ﺔﻴﻜﻠﺳﻼﻟﺍ ﺕﺎﻜﺒﺸﻟﺍ
الأربعاء مارس 07, 2012 7:14 pm من طرف Admin
» تعلم الـ JavaScript ( أساسيات كتابة الكود )
الأحد فبراير 12, 2012 3:10 pm من طرف Admin
» مكتبة الأكواد والحلول البرمجية , سوف نخصص هذا الجزء لوضع اي كود يسهل الوصول إلى عملية معينة , كما تستطيع شرح اي خاصية يمكن ان تستخدم للقيام بوظيفة معينة .
الأربعاء فبراير 08, 2012 2:38 pm من طرف Admin
» مجموعة أكواد للغة السي شارب c#
الأربعاء فبراير 08, 2012 2:28 pm من طرف Admin
» شرح عمل تصويت بتقنية AJAX.pdf
الإثنين فبراير 06, 2012 9:17 pm من طرف Admin