This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Đổi Dương Lich ra Âm Lịch
public partial class Form1 : Form { public Form1() { InitializeComponent(); } #region private string DocNamAmLich(Int64 Nam) { string[] can ={ "Giáp", "Ất", "Bính", "Đinh", "Mậu", "Kỷ", "Canh", "Tân", "Nhâm", "Quý" }; string[] chi ={ "Tý", "Sửu", "Dần", "Mẹo", "Thìn", "Tỵ", "Ngọ", "Mùi", "Thân", "Dậu", "Tuất", "Hợi" }; Int64 SoCan, SoChi, n, m; n = (Nam - 2008) % 10; m = (Nam - 2008) % 12; SoCan = (10 + 4 + n) % 10; //Nam 2008 co can la 4 (Mau), cong 10 de sau khi chia lay du duoc so duong SoChi = (12 + 0 + m) % 12;//Nam 2008 co chi la 0 (Ty), cong 12 de sau khi chia lay du duoc so duong return can[SoCan] + " " + chi[SoChi]; } #endregion
try { int tong = 0; int a; a = Convert.ToInt32(txt_Nhap.Text.ToString()); for (int i = 0; i <= a; i++) { tong += i; } lb_Ketqua.Text = tong.ToString();
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { openFileDialog1.Title = "Chọn một tập tin"; openFileDialog1.InitialDirectory = "C:\\winnt"; openFileDialog1.Filter = "Tập tin văn bản .TXT|*.txt|Tập tin .INI|*.ini|Tập tin .DLL|*.dll|Tất cả tập tin|*.*";
} private void button2_Click(object sender, EventArgs e) { openFileDialog2.Title = "Chọn nhiều tập tin"; openFileDialog2.InitialDirectory = "C:\\winnt"; openFileDialog2.Filter = "Tập tin văn bản .TXT|*.txt|Tập tin .INI|*.ini|Tập tin .DLL|*.dll|Tất cả tập tin|*.*"; openFileDialog2.ShowDialog(); string[] nhieufile = openFileDialog2.FileNames; for (int i = 1; i < nhieufile.Length; i++) { MessageBox.Show(nhieufile[i], "tập tin thứ " + i.ToString() + " là :"); } } private void button3_Click(object sender, EventArgs e)
public partial class Form1 : Form { public Form1() { InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e) { label1.Text = "Cộng hòa xã hội chủ nghĩa Việt Nam "; textBox1.Text = " ENTER se ok...(Khoang trang) "; } string s; private void timer1_Tick(object sender, EventArgs e) { s = label1.Text;
private void button1_Click(object sender, EventArgs e) { label1.Text = " Cộng hòa xã hội chủ nghĩa Việt Nam "; textBox1.Text = " ENTER se ok...(Khoang trang) "; //radioButton1.Checked = true; timer1.Interval = 50; }
}
Đệ Quy và vòng lập
11
(Hộp RichTextBoc – Button 1->4)
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private ulong GiaiThua(ulong so) { if (so == 1) return 1; else return so * GiaiThua(so - 1); } private void button1_Click(object sender, EventArgs e) { ulong x; string kq=""; x = Convert.ToUInt64(textBox1.Text); for (ulong i = 1; i <= x; i++) { kq += i + "!=" + Convert.ToString(GiaiThua(i)) + '\n'; richTextBox2.Text = kq; }
}
private void button2_Click(object sender, EventArgs e) { ulong n; ulong x = 1; string kq = ""; n = Convert.ToUInt64(textBox1.Text);
12
for (ulong i = 1; i <= n; i++) { x = x * i; kq += i + "!=" + x + '\n'; richTextBox4.Text = kq; }
public partial class Form1 : Form { public Form1() { InitializeComponent(); } int i=-1; private void Form1_Load(object sender, EventArgs e) { textBox1.Text = "Cộng hòa xã hội chủ nghĩa Việt Nam"; }
private void textBox2_KeyPress(object sender, KeyPressEventArgs e) { i++; if (i < textBox1.Text.Length) { e.KeyChar=Convert.ToChar(textBox1.Text.Substring(i,1));
23
} else e.KeyChar=Convert.ToChar(Keys.None); } }
Lịch thế giới
public partial class Form1 : Form { DateTime dt; public Form1() { InitializeComponent(); }
public partial class Form1 : Form { public Form1() { InitializeComponent(); }
private void button1_Click(object sender, EventArgs e) { int x = 5; int y = 10; int z = 15; TruyenGiaTri(x); TruyenThamKhao(ref y); TruyenVoiOUT(out z); label1.Text = Convert.ToString(x); label2.Text = Convert.ToString(y); label3.Text = Convert.ToString(z);
} private void TruyenGiaTri(int n) { n = n * 2; } private void TruyenThamKhao(ref int n) { n = n * 2; } private void TruyenVoiOUT(out int n) { n = 100; n = n * 2; } }
Cộng trừ ngày tháng giây
26
public partial class Form1 : Form { public Form1() { InitializeComponent(); }
private void button1_Click(object sender, EventArgs e) { DateTime d = dateTimePicker1.Value; double db = Convert.ToDouble(textBox1.Text); switch (comboBox1.SelectedIndex) { case 0: d = d.AddHours(db); break; case 1: d = d.AddMinutes(db); break; case 2: d = d.AddSeconds(db); break; case 3:
27
d = d.AddDays(db); break; case 4: d = d.AddMonths(Convert.ToInt16(db)); break; case 5: d = d.AddYears(Convert.ToInt16(db)); break; } label1.Text = d.ToString("dd/MM/yyyy hh:mm:ss"); }
private void inBảngSốXeToolStripMenuItem_Click(object sender, EventArgs e) { In_bang_so_xe.Form1 f1 = new In_bang_so_xe.Form1(); // show cai form cần ra ! f1.MdiParent = this; f1.Show(); } }
=============================
public partial class DeThi1 : Form { public DeThi1() { InitializeComponent(); }
partial class AboutBox1 : Form { public AboutBox1() { InitializeComponent();
37
// Initialize the AboutBox to display the product information from the assembly information. // Change assembly information settings for your application through either: // - Project->Properties->Application->Assembly Information // - AssemblyInfo.cs this.Text = String.Format("About {0}", AssemblyTitle); this.labelProductName.Text = AssemblyProduct; this.labelVersion.Text = String.Format("Version {0}", AssemblyVersion); this.labelCopyright.Text = AssemblyCopyright; this.labelCompanyName.Text = AssemblyCompany; }
#region Assembly Attribute Accessors
public string AssemblyTitle { get { // Get all Title attributes on this assembly object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false); // If there is at least one Title attribute if (attributes.Length > 0) { // Select the first one AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0]; // If it is not an empty string, return it if (titleAttribute.Title != "") return titleAttribute.Title; } // If there was no Title attribute, or if the Title attribute was the empty string, return the .exe name return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase); } }
public string AssemblyVersion { get { return Assembly.GetExecutingAssembly().GetName().Version.ToString(); } }
public string AssemblyDescription { get {
38
// Get all Description attributes on this assembly object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false); // If there aren't any Description attributes, return an empty string if (attributes.Length == 0) return ""; // If there is a Description attribute, return its value return ((AssemblyDescriptionAttribute)attributes[0]).Description; } }
public string AssemblyProduct { get { // Get all Product attributes on this assembly object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false); // If there aren't any Product attributes, return an empty string if (attributes.Length == 0) return ""; // If there is a Product attribute, return its value return ((AssemblyProductAttribute)attributes[0]).Product; } }
public string AssemblyCopyright { get { // Get all Copyright attributes on this assembly object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false); // If there aren't any Copyright attributes, return an empty string if (attributes.Length == 0) return ""; // If there is a Copyright attribute, return its value return ((AssemblyCopyrightAttribute)attributes[0]).Copyright; } }
public string AssemblyCompany { get { // Get all Company attributes on this assembly
39
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false); // If there aren't any Company attributes, return an empty string if (attributes.Length == 0) return ""; // If there is a Company attribute, return its value return ((AssemblyCompanyAttribute)attributes[0]).Company; } } #endregion
//Hàm giai thừa viết đệ quy public UInt64 GiaiThua(UInt64 so) { if (so == 1) return 1; else return so * GiaiThua(so - 1);
}
}
43
Chọn ngày tháng năm Anh Việt 1:
public partial class Form1 : Form { public Form1() { InitializeComponent(); } #region các phương thức public void nam() { cbo_nam.Items.Clear(); for (int i = 1900; i <= 2500; i++) { cbo_nam.Items.Add(i); } //cbo_nam.SelectedIndex = 0; } public void ngay_thangdu() { cbo_ngay.Items.Clear(); for (int i = 1; i <= 31; i++) { cbo_ngay.Items.Add(i); } } public void ngay_thangthieu() { cbo_ngay.Items.Clear(); for (int i = 1; i <= 30; i++) {
44
cbo_ngay.Items.Add(i); } //cbo_ngay.Text = DateTime.Now.Day.ToString(); //cbo_ngay.SelectedValue=""; } public void ngay_thanghai() { int s; cbo_ngay.Items.Clear(); if (int.Parse(cbo_nam.Text) % 4 == 0 || int.Parse(cbo_nam.Text) % 100 == 0) s=29; else s=28;
for (int i = 1; i <= s; i++) { cbo_ngay.Items.Add(i); } // cbo_ngay.Text = DateTime.Now.Day.ToString(); //cbo_ngay.SelectedValue=""; }
public void thang() { cbo_thang.Items.Clear(); for (int i = 1; i <= 12; i++) { cbo_thang.Items.Add(i); } //cbo_nam.SelectedValue; } public string docngay() { string ngay, thang, nam; ngay = cbo_ngay.Text; thang = cbo_thang.Text; nam = cbo_nam.Text; DateTime t = new DateTime(Convert.ToInt16(nam),Convert.ToInt16(thang),Convert.ToInt16(ngay)); return docthu1(t) + ", Ngày " + ngay + " Tháng " + thang + " Năm " + nam; } public string docngay_En() { string ngay, thang, nam,ngayEN; ngay = cbo_ngay.Text; thang = cbo_thang.Text; nam = cbo_nam.Text; int ng = Convert.ToInt16(cbo_ngay.Text);
45
switch (ng) { case 1: case 11: case 21: case 31: ngayEN = "st "; break; case 2: case 12: case 22: ngayEN = "rd "; break; default : ngayEN = "th "; break; }
DateTime t = new DateTime(Convert.ToInt16(nam), Convert.ToInt16(thang), Convert.ToInt16(ngay)); return t.ToString("dddd") + ", " + t.ToString("dd") + ngayEN + " " + t.ToString("MMMM") + " " + t.ToString("yyyy"); } public string docthu(DateTime dt) { String str = ""; //DateTime dt; switch (dt.DayOfWeek) { case DayOfWeek.Monday: str = "Thứ hai"; break; case DayOfWeek.Tuesday: str = "Thứ ba"; break; case DayOfWeek.Wednesday: str = "Thứ tư"; break; case DayOfWeek.Thursday: str = "Thứ năm"; break; case DayOfWeek.Friday: str = "Thứ sáu"; break; case DayOfWeek.Saturday: str = "Thứ bảy"; break; case DayOfWeek.Sunday: str = "Chủ nhật"; break;
46
} return str;
}
public string docthu1(DateTime dt) { String str = ""; // DateTime dt; switch (dt.DayOfWeek.GetHashCode()) { case 1: str = "Thứ hai"; break; case 2: str = "Thứ ba"; break; case 3: str = "Thứ tư"; break; case 4: str = "Thứ năm"; break; case 5: str = "Thứ sáu"; break; case 6: str = "Thứ bảy"; break; case 0: str = "Chủ nhật"; break;
} return str;
} public void chonNgay() { switch (int.Parse(cbo_thang.Text)) { case 1: ngay_thangdu(); break; case 3: ngay_thangdu(); break; case 5: ngay_thangdu(); break; case 7: ngay_thangdu(); break;
47
case 8: ngay_thangdu(); break; case 10: ngay_thangdu(); break; case 12: ngay_thangdu(); break; case 4: ngay_thangthieu(); break; case 6: ngay_thangthieu(); break; case 9: ngay_thangthieu(); break; case 11: ngay_thangthieu(); break; case 2: ngay_thanghai(); break; } } #endregion
Random randomNumber = new Random(); int[] frequency = new int[ 7 ];
public RollDie() { // // Required for Windows Form Designer support // InitializeComponent(); }
/// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if ( disposing ) { if ( components != null ) { components.Dispose(); } }
base.Dispose( disposing ); }
#region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RollDie)); this.dieLabel10 = new System.Windows.Forms.Label(); this.dieLabel4 = new System.Windows.Forms.Label(); this.dieLabel5 = new System.Windows.Forms.Label(); this.dieLabel6 = new System.Windows.Forms.Label(); this.dieLabel7 = new System.Windows.Forms.Label(); this.dieLabel1 = new System.Windows.Forms.Label();
55
this.dieLabel2 = new System.Windows.Forms.Label(); this.dieLabel3 = new System.Windows.Forms.Label(); this.displayTextBox = new System.Windows.Forms.RichTextBox(); this.dieLabel8 = new System.Windows.Forms.Label(); this.dieLabel9 = new System.Windows.Forms.Label(); this.rollButton = new System.Windows.Forms.Button(); this.dieLabel12 = new System.Windows.Forms.Label(); this.dieLabel11 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // dieLabel10 // this.dieLabel10.Location = new System.Drawing.Point(235, 90); this.dieLabel10.Name = "dieLabel10"; this.dieLabel10.Size = new System.Drawing.Size(56, 48); this.dieLabel10.TabIndex = 2; // // dieLabel4 // this.dieLabel4.Location = new System.Drawing.Point(235, 34); this.dieLabel4.Name = "dieLabel4"; this.dieLabel4.Size = new System.Drawing.Size(56, 48); this.dieLabel4.TabIndex = 2; // // dieLabel5 // this.dieLabel5.Location = new System.Drawing.Point(299, 34); this.dieLabel5.Name = "dieLabel5"; this.dieLabel5.Size = new System.Drawing.Size(56, 48); this.dieLabel5.TabIndex = 2; // // dieLabel6 // this.dieLabel6.Location = new System.Drawing.Point(363, 34); this.dieLabel6.Name = "dieLabel6"; this.dieLabel6.Size = new System.Drawing.Size(56, 48); this.dieLabel6.TabIndex = 2; // // dieLabel7 // this.dieLabel7.Location = new System.Drawing.Point(43, 90); this.dieLabel7.Name = "dieLabel7"; this.dieLabel7.Size = new System.Drawing.Size(56, 48); this.dieLabel7.TabIndex = 2; // // dieLabel1 // this.dieLabel1.Location = new System.Drawing.Point(43, 34); this.dieLabel1.Name = "dieLabel1"; this.dieLabel1.Size = new System.Drawing.Size(56, 48);
56
this.dieLabel1.TabIndex = 2; // // dieLabel2 // this.dieLabel2.Location = new System.Drawing.Point(107, 34); this.dieLabel2.Name = "dieLabel2"; this.dieLabel2.Size = new System.Drawing.Size(56, 48); this.dieLabel2.TabIndex = 2; // // dieLabel3 // this.dieLabel3.Location = new System.Drawing.Point(171, 34); this.dieLabel3.Name = "dieLabel3"; this.dieLabel3.Size = new System.Drawing.Size(56, 48); this.dieLabel3.TabIndex = 2; // // displayTextBox // this.displayTextBox.BackColor = System.Drawing.Color.Gold; this.displayTextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.980198F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.displayTextBox.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(192))))); this.displayTextBox.Location = new System.Drawing.Point(32, 241); this.displayTextBox.Name = "displayTextBox"; this.displayTextBox.Size = new System.Drawing.Size(399, 147); this.displayTextBox.TabIndex = 0; this.displayTextBox.Text = ""; // // dieLabel8 // this.dieLabel8.Location = new System.Drawing.Point(107, 90); this.dieLabel8.Name = "dieLabel8"; this.dieLabel8.Size = new System.Drawing.Size(56, 48); this.dieLabel8.TabIndex = 2; // // dieLabel9 // this.dieLabel9.Location = new System.Drawing.Point(171, 90); this.dieLabel9.Name = "dieLabel9"; this.dieLabel9.Size = new System.Drawing.Size(56, 48); this.dieLabel9.TabIndex = 2; // // rollButton // this.rollButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.980198F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.rollButton.Location = new System.Drawing.Point(136, 173); this.rollButton.Name = "rollButton"; this.rollButton.Size = new System.Drawing.Size(188, 40);
57
this.rollButton.TabIndex = 1; this.rollButton.Text = "Sinh 12 mặt ngẫu nhiên"; this.rollButton.Click += new System.EventHandler(this.rollButton_Click); // // dieLabel12 // this.dieLabel12.Location = new System.Drawing.Point(363, 90); this.dieLabel12.Name = "dieLabel12"; this.dieLabel12.Size = new System.Drawing.Size(56, 48); this.dieLabel12.TabIndex = 2; // // dieLabel11 // this.dieLabel11.Location = new System.Drawing.Point(299, 90); this.dieLabel11.Name = "dieLabel11"; this.dieLabel11.Size = new System.Drawing.Size(56, 48); this.dieLabel11.TabIndex = 2; // // RollDie // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(463, 416); this.Controls.Add(this.dieLabel11); this.Controls.Add(this.dieLabel10); this.Controls.Add(this.dieLabel12); this.Controls.Add(this.dieLabel9); this.Controls.Add(this.dieLabel7); this.Controls.Add(this.dieLabel6); this.Controls.Add(this.dieLabel8); this.Controls.Add(this.dieLabel5); this.Controls.Add(this.dieLabel4); this.Controls.Add(this.dieLabel3); this.Controls.Add(this.dieLabel2); this.Controls.Add(this.dieLabel1); this.Controls.Add(this.rollButton); this.Controls.Add(this.displayTextBox); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); // nằm trong thư mự bin/debug/image/ this.Name = "RollDie"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Sinh số ngẫu nhiên cho xúc xắc"; this.ResumeLayout(false);
}#endregion
/// <summary> /// The main entry point for the application. /// </summary> [STAThread]
58
static void Main() { Application.Run( new RollDie() ); }
private void rollButton_Click( object sender, System.EventArgs e ) { // pass the labels to a method that will // randomly assign a face to each die DisplayDie( dieLabel1 ); DisplayDie( dieLabel2 ); DisplayDie( dieLabel3 ); DisplayDie( dieLabel4 ); DisplayDie( dieLabel5 ); DisplayDie( dieLabel6 ); DisplayDie( dieLabel7 ); DisplayDie( dieLabel8 ); DisplayDie( dieLabel9 ); DisplayDie( dieLabel10 ); DisplayDie( dieLabel11 ); DisplayDie( dieLabel12 );
double total = 0;
for ( int i = 1; i < 7; i++ ) total += frequency[ i ];
displayTextBox.Text = "Mặt\tSố lần\t\tTỉ lệ\n";
// output frequency values for ( int x = 1; x < frequency.Length; x++ ) { displayTextBox.Text += x + "\t" + frequency[ x ] + "\t\t" + String.Format( "{0:N}", frequency[ x ] / total * 100 ) + "%\n"; }
} // end rollButton_Click
// simulates roll, display proper // image and increment frequency public void DisplayDie( Label dieLabel ) { int face = randomNumber.Next( 1, 7 );
private void button2_Click(object sender, EventArgs e) { double x = Convert.ToDouble(textBox1.Text); double y = Convert.ToDouble(textBox2.Text); lblKQ.Text = Convert.ToString(x - y);
}
private void button3_Click(object sender, EventArgs e) { double x = Convert.ToDouble(textBox1.Text); double y = Convert.ToDouble(textBox2.Text); lblKQ.Text = Convert.ToString(x * y);
} }
Hinhtron và elip tai. 1 diem.
public partial class Form1 : Form { public Form1() { InitializeComponent(); }
private void button1_Click(object sender, EventArgs e) { System.Drawing.Pen myPen; myPen = new System.Drawing.Pen(System.Drawing.Color.Red); System.Drawing.Graphics formGraphics = this.CreateGraphics(); formGraphics.DrawEllipse(myPen,10,20,100,200);//X,Y,Width,Heght của hình chữ nhật đường bao myPen.Dispose();
65
formGraphics.Dispose(); }
private void button2_Click(object sender, EventArgs e) { System.Drawing.Pen myPen; myPen = new System.Drawing.Pen(System.Drawing.Color.Red); System.Drawing.Graphics formGraphics = this.CreateGraphics(); formGraphics.DrawEllipse(myPen,10,20,200,200);//X,Y,Width,Heght của hình chữ nhật đường bao myPen.Dispose(); formGraphics.Dispose(); }
Đường thẳng – chữ nhật – elip (Vẽ từ dưới lên !!!)
public partial class Form1 : Form { Graphics g; SolidBrush brush = new SolidBrush(Color.Blue); Pen pen = new Pen(Color.Blue); Point p1 = new Point(); public Form1() { InitializeComponent(); }
private void panel1_MouseUp(object sender, MouseEventArgs e) { Point p2 = new Point(); p2.X = e.X; p2.Y = e.Y;
int m; if ((p1.X > p2.X) && (e.Button != MouseButtons.Left)) { m = p1.X; p1.X = p2.X; p2.X = m; } if ((p1.Y > p2.Y) && (e.Button != MouseButtons.Left)) { m = p1.Y; p1.Y = p2.Y; p2.Y = m; }
switch (e.Button) { case MouseButtons.Left: g.DrawLine(pen, p1.X, p1.Y, e.X, e.Y); break; case MouseButtons.Middle: g.FillRectangle(brush, p1.X, p1.Y, p2.X - p1.X, p2.Y - p1.Y); break; case MouseButtons.Right:
// Form contains several RadioButtons--user chooses one// from each group to create a custom MessageBoxpublic partial class RadioButtonsTestForm : Form{ // create variables that store the user's choice of options private MessageBoxIcon iconType; private MessageBoxButtons buttonType;
// default constructor public RadioButtonsTestForm() { InitializeComponent(); } // end constructor
// change Buttons based on option chosen by sender private void buttonType_CheckedChanged( object sender, EventArgs e ) { if ( sender == okButton ) // display OK Button
77
buttonType = MessageBoxButtons.OK;
// display OK and Cancel Buttons else if ( sender == okCancelButton ) buttonType = MessageBoxButtons.OKCancel;
// display Abort, Retry and Ignore Buttons else if ( sender == abortRetryIgnoreButton ) buttonType = MessageBoxButtons.AbortRetryIgnore;
// display Yes, No and Cancel Buttons else if ( sender == yesNoCancelButton ) buttonType = MessageBoxButtons.YesNoCancel;
// display Yes and No Buttons else if ( sender == yesNoButton ) buttonType = MessageBoxButtons.YesNo;
// only on option left--display Retry and Cancel Buttons else buttonType = MessageBoxButtons.RetryCancel; } // end method buttonType_Changed
// change Icon based on option chosen by sender private void iconType_CheckedChanged( object sender, EventArgs e ) { if ( sender == asteriskButton ) // display asterisk Icon iconType = MessageBoxIcon.Asterisk;
// display exclamation point Icon else if ( sender == exclamationButton ) iconType = MessageBoxIcon.Exclamation;
// display hand Icon else if ( sender == handButton ) iconType = MessageBoxIcon.Hand;
// display information Icon else if ( sender == informationButton ) iconType = MessageBoxIcon.Information;
// display question mark Icon else if ( sender == questionButton ) iconType = MessageBoxIcon.Question;
// display stop Icon
78
else if ( sender == stopButton ) iconType = MessageBoxIcon.Stop;
// only one option left--display warning Icon else iconType = MessageBoxIcon.Warning; } // end method iconType_CheckChanged
// display MessageBox and Button user pressed private void displayButton_Click( object sender, EventArgs e ) { // display MessageBox and store // the value of the Button that was pressed DialogResult result = MessageBox.Show( "This is your Custom MessageBox.", "Custon MessageBox", buttonType, iconType, 0, 0 );
// check to see which Button was pressed in the MessageBox // change text displayed accordingly switch (result) { case DialogResult.OK: displayLabel.Text = "OK was pressed."; break; case DialogResult.Cancel: displayLabel.Text = "Cancel was pressed."; break; case DialogResult.Abort: displayLabel.Text = "Abort was pressed."; break; case DialogResult.Retry: displayLabel.Text = "Retry was pressed."; break; case DialogResult.Ignore: displayLabel.Text = "Ignore was pressed."; break; case DialogResult.Yes: displayLabel.Text = "Yes was pressed."; break; case DialogResult.No: displayLabel.Text = "No was pressed."; break; } // end switch }
} // end method displayButton_Click} // end class RadioButtonsTestForm
Đoán xúc xắc79
public partial class Form1 : Form { public Form1() { InitializeComponent(); } int x = 0; private void button1_Click(object sender, EventArgs e) { label1.Image = Image.FromFile(Directory.GetCurrentDirectory() + "\\Images\\die1.gif"); x = 1;
private void Number_Click(object sender, EventArgs e) { // Nếu như là vừa bắt đầu nhập giá trị // hoặc là vừa nhấn nút phép tính ( + - X / %) if (flag || txtDisplay.Text == "0") { // Xóa dữ liệu trong ô textbox txtDisplay.Text = ""; flag = false; } // Đưa giá trị từ button vừa nhấn vào ô textbox ở vị trí sau cùng txtDisplay.AppendText(((Button)sender).Text); }
private void btnBack_Click(object sender, EventArgs e) { // Nếu ô text box có nhiều hơn 1 ký tự if (txtDisplay.TextLength > 1) { // Nếu ký tự cuối cùng là dấu chấm '.' // thì sẽ bỏ cả dấu chấm và số trước dấu chấm // đây là hàm Remove của kiểu string // có 2 đối số là vị trí bắt đầu bỏ bớt, và số ký tự sẽ bỏ ra khỏi chuỗi if (txtDisplay.Text.EndsWith(".")) txtDisplay.Text = txtDisplay.Text.Remove(txtDisplay.TextLength - 2, 2); else // không thì chỉ bỏ bớt một ký tự cuối cùng txtDisplay.Text = txtDisplay.Text.Remove(txtDisplay.TextLength - 1, 1); } else if (txtDisplay.TextLength == 1) { // Nếu chỉ có một ký tự trong ô textbox thì set giá trị về 0 // Ví dụ ô có giá trị là '9' ==> '0' txtDisplay.Text = "0"; } }
private void btnDec_Click(object sender, EventArgs e) { // Nếu không phải là số thập phân thì chèn thêm dấu chấm '.' vào if (!txtDisplay.Text.Contains(".")) txtDisplay.AppendText("."); }
88
private void PhepTinh_Click(object sender, EventArgs e) { // Lấy button vừa nhấn Button cur = (Button)sender; // Gán phép tính vào biến cPhepTinh = cur.Text[0]; // bật cờ xác định là vừa thiết lập phép tính flag = true; // nếu như giá trị của dTotal là 0 // hoặc là vừa tính toán xong if (dTotal == 0 || isGetResult) { dTotal = Convert.ToDouble(txtDisplay.Text); isGetResult = false; return; // Thoát khỏi hàm } switch (cPhepTinh) { case '+': dTotal += Convert.ToDouble(txtDisplay.Text); break; case '-': dTotal -= Convert.ToDouble(txtDisplay.Text); break; case 'X': dTotal *= Convert.ToDouble(txtDisplay.Text); break; case '/': dTotal /= Convert.ToDouble(txtDisplay.Text); break; case '%': dTotal %= Convert.ToDouble(txtDisplay.Text); break; default: break; } txtDisplay.Text = dTotal.ToString(); }
private void btnResult_Click(object sender, EventArgs e) { if (cPhepTinh == ' ') return; switch (cPhepTinh) { case '+': dTotal += Convert.ToDouble(txtDisplay.Text); break; case '-':
private string ReadNum(string strNum) { // hàm devide là chia chiều dài của chuỗi số với 3 // hàm ceiling là lấy số nguyên bé nhất lớn hơn số được lấy. ví dụ: ceiling của 3,2 là 4 // vì khi đọc số chúng ta đọc mỗi lần 3 số hàng trăm, hàng chục, hàng đơn vị int count = Convert.ToInt32(Math.Ceiling(decimal.Divide(strNum.Length, 3)));
string[] arr = new string[count]; string[] arr2 = new string[count];
int i = 0, j = 0; while (strNum.Length > 0) { // Ví dụ chuỗi 123456 // lấy chữ số 6 đưa vào mảng sẽ là 6
91
// sau đó loại chữ số 6 ra khỏi chuỗi, lúc này chuỗi sẽ thành 12345 // chữ số 6 được đưa vào mảng sẽ là 6 ở vị trí 0 trong mảng // tiếp tục lấy chữ số cuối cùng của mảng mới, lúc này là chữ số 5 // lúc này ở vị trí 0 trong mảng arr sẽ có giá trị là 56 // tiếp tục lặp lại bước trên giá trị của vị trí 0 trong mảng arr sẽ là 456 // mảng ban đầu sẽ còn lại 123 // tiếp tục lặp lại các bước trên // sau khi hoàn tất ta sẽ có mảng arr chứa hai giá trị là arr[0] = 456, arr[1] = 123
//========== Các bước chi tiết ============//
// Lấy chữ số ở vị trí cuối cùng của mảng arr[i] = strNum[strNum.Length - 1].ToString() + arr[i]; // bỏ chữ số ở vị trí cuối cùng (vừa lấy ở trên) ra khỏi chuỗi strNum = strNum.Remove(strNum.Length - 1, 1); j++; // Khi đã lấy đủ 3 chữ số thì cho mảng arr tăng lên thêm 1 index (i) // reset counter (j) về = 0; if (j == 3) { j = 0; i++; } }
// Sau khi chia chuỗi ký tự thành nhiều chuỗi nhỏ mỗi chuỗi có nhiều nhất là 3 chữ số // ta bắt đầu đọc lần lượt các chuỗi số đó
string rs = ""; for (int k = arr.Length - 1; k >= 0; k--) { // Nếu chuỗi chứa 3 giá trị 0 ==> không cần đọc if (arr[k] != "000") { rs += ReadThreeNum(arr[k]).Trim(); // ví dụ ta có chuỗi là 789456123 // thì mảng arr có 3 giá trị là 123, 456, 789 // khi ta đọc thì sẽ đọc 789 trước (đọc ngược mảng arr) // nếu k > 0 tức là không phải đọc chuỗi ký tự sau cùng // thì ta sẽ lấy ký tự ở vị trí (phần dư của k - 1 chia cho 3) trong mảng arrB // ví dụ là chuỗi trên, khi đọc chuỗi ở vị trí k là 2 thì ta sẽ có phần dư là (2 - 1) % 3 = 1 // ứng với giá trị là triệu // khi này ta sẽ có giá trị của rs sau khi gọi hàm ReadThreeNum(789) là bảy trăm tám mươi chín // ta thêm chữ 'triệu' vào sẽ được 'bảy trăm tám mươi chín triệu' // tương tự khi ta đọc tiếp chuỗi 456 // rs = bảy trăm tám mươi chín triệu bốn trăm năm mươi sáu // kiểm tra tiếp k, khi này k có giá trị là 1 // (1 - 1) % 3 = 0 vậy ứng với chữ 'ngàn' trong mảng arrB
92
// chuỗi còn lại là 123, sau khi gọi hàm ReadThreeNum thì ta được một trăm hai mươi ba // vì lúc này k = 0 nên chúng ta dừng ko kiểm tra tiếp // vậy chuỗi rs sẽ là bảy trăm tám mươi chín triệu bốn trăm năm mươi sáu ngàn một trăm hai mươi ba rs += (k > 0 ? " " + arrB[(k - 1) % 3] : ""); rs += "\r\n"; // \r có nghĩa là break line (ngắt dòng) \n có nghĩa là newline(xuống dòng) } } return rs.Trim(); }
private string ReadThreeNum(string strNum) { string rs = ""; int curnum = 0; bool flag = false;
// bắt đầu đọc số // kiểm tra nếu chuỗi đưa vào có 3 ký tự thì sẽ có hàng trăm // nên chúng ta sẽ đọc hàng trăm trước if (strNum.Length == 3) { // chuyển ký tự đầu tiên (hàng trăm) sang dạng số curnum = Convert.ToInt32(strNum[0].ToString()); // Nếu gặp trường hợp giá trị hàng trăm = 0 nhưng ở hàng chục hoặc hàng đơn vị khác 0 // thì chúng ta đọc thành không trăm // ví dụ 012 sẽ là không trăm mười hai // hoặc 001 sẽ là không trăm linh một if (strNum[0] == '0' && (strNum[1] != '0' || strNum[2] != '0')) rs += "không trăm "; else // nếu không phải là không trăm thì ta dựa vào mảng arrA để đọc giá trị của số đó và thêm chữ 'trăm' vào sau rs += arrA[curnum] + " trăm "; // loại chữ số đầu tiên ra khỏi chuỗi // ví dụ 123 ==> bỏ số 1 ra còn lại 23 strNum = strNum.Remove(0, 1); } // tương tự ta kiểm tra nếu chuỗi có 2 ký tự thì có hàng chục // ta bắt đầu đọc hàng chục if (strNum == "00") return rs;
if (strNum.Length == 2) { // chuyển ký tự đầu tiên (hàng chục) sang dạng số curnum = Convert.ToInt32(strNum[0].ToString()); // nếu giá trị là 0 thì nó sẽ là 'linh' // ví dụ 01 == linh một, 02 == linh 2
93
// nếu là 1 thì sẽ là mười, vì trong mảng arrA chúng ta mặc định giá trị ở vị trí 1 là chữ 'một' if (curnum == 0) rs += "linh "; else if (curnum == 1) rs += "mười "; else { // các trường hợp còn lại thì chúng ta dựa vào mảng arrA để đọc lên chữ số đó // bật cờ để dánh dấu là không phải 'linh' hoặc 'mười' // vì khi nếu là mười và giá trị của hàng đơn vị là 1 thì phải đọc là mười một // còn các trường hợp khác là mốt ví dụ: hai mươi mốt, ba mươi mốt flag = true; rs += arrA[curnum] + " mươi "; } // tương tự như trên la loại chữ số vừa đọc ra khỏi chuỗi strNum = strNum.Remove(0, 1); }
// nếu chuỗi có giá trị là 0 thì ko cần đọc tiếp if (strNum == "0") return rs;
if (strNum.Length == 1) { // chuyển ký tự đầu tiên (hàng đơn vị) sang dạng số curnum = Convert.ToInt32(strNum[0].ToString()); // nếu giá trị hàng đơn vị là 1 và có bật cờ thì chúng ta điền giá trị là 'mốt' vào if (curnum == 1 && flag) rs += "mốt"; else if (curnum == 5) // nếu giá trị là 5 thì sẽ là 'lăm'. ví dụ hai mươi lăm, mười lăm, v.v... rs += "lăm"; else rs += arrA[curnum]; // các trường hợp khác thì dựa vào mảng arrA để đọc lên } return rs.Trim(); } }
94
Ảnh di chuyển lên xuống
public partial class frmAnhDong : Form { public frmAnhDong() { InitializeComponent(); }
public partial class frmAnimatedText : Form { public frmAnimatedText() { InitializeComponent(); } int intCurrentGradientShift = 10; int intGradiantStep = 5; string text = "Trần Bách Thành "; string left = "", right = "";
private void tmrMain_Tick(object sender, EventArgs e) { Graphics grfx = CreateGraphics(); grfx.Clear(SystemColors.Control); Font font = new Font("Times New Roman", 30,
96
FontStyle.Bold, GraphicsUnit.Point); left = text.Substring(0, 1); right = text.Substring(1); text = right + left; SizeF sizfText = new SizeF(grfx.MeasureString(text, font));
private void bt_hetphai_Click(object sender, EventArgs e) { int n = lbox_Trai.Items.Count;
lbox_Trai.SelectedIndex = 0;
for (int i = 0; i < n; i++) { try { lbox_phai.Items.Add(lbox_Trai.SelectedItem); lbox_Trai.Items.Remove(lbox_Trai.SelectedItem); lbox_Trai.SelectedIndex = 0; } catch
101
{ } } }
private void bt_mottrai_Click(object sender, EventArgs e) { int n = lbox_phai.SelectedItems.Count; if (n == 0) { MessageBox.Show("Chon 1 cai di !"); } else { for (int i = 0; i < n; i++) { lbox_Trai.Items.Add(lbox_phai.SelectedItem); lbox_phai.Items.Remove(lbox_phai.SelectedItem); } } }
private void bt_hettrai_Click(object sender, EventArgs e) { int n = lbox_phai.Items.Count;
lbox_phai.SelectedIndex = 0;
for (int i = 0; i < n; i++) { try { lbox_Trai.Items.Add(lbox_phai.SelectedItem); lbox_phai.Items.Remove(lbox_phai.SelectedItem); lbox_phai.SelectedIndex = 0; } catch { } } } }
102
Lấy số ngẫu nhiên
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button_ngaunhien_trunglap_Click(object sender, EventArgs e) { Form2 frm = new Form2(); Random ran = new Random(); frm.ShowDialog(); for (int i = 0; i <= frm.so; i++) { listBox_so.Items.Add(ran.Next(int.Parse(textBox_tu.Text), int.Parse(textBox_den.Text))); } } private void button_thoat_Click(object sender, EventArgs e) { Close(); }
private void button_ngaunhien_kotrunglap_Click(object sender, EventArgs e) {// Sub SoNgauNhienKoLapLai(ByVal SoMax)// 'Tao mot Array de chua so// ReDim iSoArray(SoMax) As Integer// Dim So1 As Integer, So2 As Integer
103
// Randomize // For So1 = 1 To SoMax//TimSoMoi:// So2 = 1// 'Tim so// iSoArray(So1) = Int((SoMax - 1 + 1) * Rnd + 1) // 'neu So2=So1 moi vao so sanh, vi khi So2<So1 thi// 'nhung so trong Array den So1 da duoc so sach.// Do Until So2 = So1// 'neu so moi tim giong so trong array thi di tim so moi// If iSoArray(So1) = iSoArray(So2) Then GoTo TimSoMoi// So2 = So2 + 1// Loop// Next // 'TEST// Dim i As Integer// For i = 1 To SoMax// Debug.Print iSoArray(i)// Next//End Sub }
/Mảng có dộ dài cố định phải chứa các đối tượng cùng loại. //Một mảng ArrayList có thể lưu trữ các đối tượng thuộc các loại khác nhau.
namespace Baitap3_Container___Muctieu2{ class Program { static void Main(string[] args) { ArrayList al = new ArrayList(); al.Add("Hello"); al.Add("15,16,17"); al.Add(new DateTime(2010, 5, 30)); Console.WriteLine (al[0]); Console.WriteLine(); Console.WriteLine(al[1]); Console.WriteLine(); Console.WriteLine(al[2]); Console.WriteLine(); Console.ReadLine();b. Containernamespace Baitap3_Container___Muctieu3{ class Program { static void Main(string[] args) { Queue/*<string>*/ q = new Queue/*<string>*/(); q.Enqueue("ABC"); q.Enqueue("123"); q.Enqueue(new Decimal(15.30)); q.Enqueue(new DateTime(2002,5,10)); Console.WriteLine(q.Dequeue()); Console.WriteLine(q.Dequeue()); Console.WriteLine(q.Dequeue()); Console.WriteLine(q.Dequeue()); Console.ReadLine(); /*foreach ( String a in q) Console.WriteLine(q.Dequeue()); Console.ReadLine();*/c. Định nghĩa Lớpnamespace Baitap3_DinhNghiaLop{ class Program { static void Main(string[] args) { A myA = new A(); A.Static_Member(); myA.Instance_Member(); Console.WriteLine();
109
B myB= new B(); myB.Instance_Member(); B.Static_Member(); Console.WriteLine(); Console.WriteLine("Bien X = " + myB.X); Console.Write(myB.Y); Console.WriteLine("Bien Y = " ); Console.WriteLine("Bien Z = " + myB.Z); Console.ReadLine(); } class A { static public void Static_Member()//Khai bao static thi tu ham main co the goi truc tiep phuong thuc { Console.WriteLine("Calling from Static Member"); } public void Instance_Member()//Khai bao public thi ham Main fai new lop A moi goi dc phuong thuc { Console.WriteLine("Calling from Instance Member"); } } class B : A //Lop B ke thua tu A nen co the goi cac phuong thuc trong class A { private int x; private int y; private int z; public int X { get { return x; } } public int Y { set { y=value;} } public int Z { get { return z; } set {z=value;}d. Tính giá trị Max của biến Bytenamespace TinhToan{ class Tinhtoan { static void Main() { byte b; b = byte.MaxValue; Console.WriteLine("Maximum Byte is " + b.ToString ());
110
Console.ReadLine(); }e. Xuất ra 1 chuỗi namespace XuatChuoi{ class Program { static void Main(string[] args) { int[] i = new int[5] { 40, 30, 60, 80, 100 }; int j; for (j = 0; j < 5; j++) { Console.WriteLine("Index = " + j.ToString() + " & Value = " + i[j].ToString()); Console.ReadLine(); } string[] str = new string[3] { "I", "LOVE", "U" }; int iStr; for (iStr = 0; iStr < 3; iStr++) { Console.WriteLine("Index = " + iStr.ToString() + " & Value = " + str[iStr]); Console.ReadLine(); } DateTime[] date = new DateTime[2] { new DateTime(2010, 3, 20,20,30,55), new DateTime(2009, 12, 30,9,40,59) }; int iDate; foreach (DateTime s in date) Console.WriteLine("Index = " + s.ToString() + " & Value = " + s.ToString()); Console.ReadLine();
Các phép toán số học & logic
namespace Bai1d{ public partial class Form1 : Form
111
{ private void button_thoat_Click(object sender, EventArgs e) { this.Close(); } private void button_and_Click(object sender, EventArgs e) { } private int dichchuyentrai() { int a = int.Parse(textBox_so1.Text); int b = int.Parse(textBox_so2.Text); int c = a << b; return c; } private int dichchuyenphai() { int a = int.Parse(textBox_so1.Text); int b = int.Parse(textBox_so2.Text); int c = a >> b; return c; } private void button_dichphai_Click(object sender, EventArgs e) { textBox_kq.Text = dichchuyentrai().ToString(); }
#region Cac phuong thuc private void moveup() { x = pictureBox1.Location.X; y = pictureBox1.Location.Y; pictureBox1.Location = new System.Drawing.Point(x, y - 10); } private void movedown() { x = pictureBox1.Location.X; y = pictureBox1.Location.Y; pictureBox1.Location = new System.Drawing.Point(x, y + 10); }
113
private void moveleft() { x = pictureBox1.Location.X; y = pictureBox1.Location.Y; pictureBox1.Location = new System.Drawing.Point(x-10 ,y); } private void moveright() { x = pictureBox1.Location.X; y = pictureBox1.Location.Y; pictureBox1.Location = new System.Drawing.Point(x + 10, y); } private void reset() { x = pictureBox1.Location.X; y = pictureBox1.Location.Y; pictureBox1.Location = new System.Drawing.Point(x_old,y_old); } #endregion
private void timer_tg_Tick(object sender, EventArgs e) { x = pictureBox1.Location.X; y = pictureBox1.Location.Y; pictureBox1.Location = new System.Drawing.Point(x + 10, y); if (x >= this.Width) x = 0; pictureBox1.Location = new System.Drawing.Point(x + 10, y); }
c. Tự động chạy : (Chay 2chieu)namespace BTChuong3{ public partial class DienkhienControl_Chay2chieu : Form { bool thuan; public DienkhienControl_Chay2chieu() { InitializeComponent(); } private void timer_h_Tick(object sender, EventArgs e) { Point p = pictureBox1.Location; if (p.X >= (this.Width - pictureBox1.Width)) thuan = false; else if (p.X < 0) thuan = true; if (thuan) pictureBox1.Location = new Point(p.X + 5, p.Y); else pictureBox1.Location = new Point(p.X - 5, p.Y); }
namespace Dialog{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } OpenFileDialog open;
private void btn1TapTin_Click(object sender, EventArgs e) { open = new OpenFileDialog(); open.InitialDirectory = "C:\\windows"; open.Title = "Chọn 1 tập tin"; open.Filter = "Các tập tin DLL|*.dll|Các tập tin INI và LOG|*.ini;*.log|Tất cả các tập tin|*.*"; open.ShowDialog(); txtThongBao.Text = open.FileName; }
private void btnNhieuTapTin_Click(object sender, EventArgs e) { open = new OpenFileDialog(); open.Multiselect = true;
open.InitialDirectory = "C:\\windows"; open.Title = "Chọn 1 tập tin"; open.Filter = "Các tập tin DLL|*.dll|Các tập tin INI và LOG|*.ini;*.log|Tất cả các tập tin|*.*"; open.ShowDialog(); string[] text= open.FileNames; txtThongBao.Text="Có tất cả "+text.Length.ToString()+" tập tin: \r\n"; foreach (string s in text) { txtThongBao.Text += s + "\r\n"; } }
} ColorDialog color; private void btnMauNen_Click(object sender, EventArgs e) { color = new ColorDialog(); DialogResult rs=color.ShowDialog(); if (rs == DialogResult.OK) txtThongBao.BackColor = color.Color; }
private void btnMauChu_Click(object sender, EventArgs e) { color = new ColorDialog(); DialogResult rs = color.ShowDialog(); if (rs == DialogResult.OK) txtThongBao.ForeColor = color.Color; } FontDialog font; private void btnFont_Click(object sender, EventArgs e) { font = new FontDialog(); DialogResult rs = font.ShowDialog(); if (rs == DialogResult.OK) txtThongBao.Font = font.Font; }
private void btnReset_Click(object sender, EventArgs e) { txtThongBao.Text = "Ví dụ lập trình C# sử dụng các hộp thoại thông dụng của hệ điều hành Windows"; txtThongBao.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold); txtThongBao.BackColor = System.Drawing.Color.SandyBrown; txtThongBao.ForeColor = System.Drawing.Color.Blue; }
namespace VeHinhChuNhat{ public partial class Form1 : Form { Graphics g; Pen Mypen = new Pen(Color.Blue, 1); Point p1 = new Point(); //Point p2 = new Point(); SolidBrush Mybrush = new SolidBrush(Color.Blue);
public Form1() {
118
InitializeComponent(); g = this.CreateGraphics(); }
int a, b; a = e.X - p1.X; b = e.Y - p1.Y; if (a < 0 && b < 0) { a = a * (-1); b = b * (-1); g.DrawRectangle(Mypen, e.X, e.Y, a, b); } else if (a > 0 && b < 0) { b = b * (-1); g.DrawRectangle(Mypen,p1.X,e.Y, a, b); } else if (a < 0 && b >0) { a = a * (-1); g.DrawRectangle(Mypen, e.X, p1.Y, a, b); } else g.DrawRectangle(Mypen, p1.X, p1.Y, e.X - p1.X, e.Y - p1.Y); //g.Dispose();
119
//Mypen.Dispose(); } break; case MouseButtons.Right: { System.Drawing.SolidBrush mybrush1; mybrush1 = new System.Drawing.SolidBrush(System.Drawing.Color.Blue); // g.FillRectangle(mybrush1, p1.X, p1.Y, e.X - p1.X, e.Y - p1.Y); int a, b; a = e.X - p1.X; b = e.Y - p1.Y; if (a < 0 && b < 0) { a = a * (-1); b = b * (-1); g.FillRectangle(Mybrush, e.X, e.Y, a, b); } else if (a<0 && b>0) { a = a * (-1); g.FillRectangle(Mybrush, e.X, p1.Y, a, b); } else if (a > 0 && b < 0) { b = b * (-1); g.FillRectangle(Mybrush, p1.X, e.Y, a, b); } else g.FillRectangle(Mybrush, p1.X, p1.Y, e.X - p1.X, e.Y - p1.Y); } break; case MouseButtons.Middle: { g.DrawLine(Mypen, p1.X, p1.Y, e.X, e.Y); } break; } } private void Form1_MouseDown(object sender, MouseEventArgs e) { p1.X = e.X; p1.Y = e.Y; } private void button_xoamau_Click(object sender, EventArgs e) { this.Refresh(); }
120
b.Vẽ Hình Eclipse
121
122
c. Notepad
namespace NotePad{ public partial class NotePad : Form { public NotePad() { InitializeComponent(); } private void ClearFont() { timesNewRomanToolStripMenuItem.Checked = false; arialToolStripMenuItem.Checked = false; courierToolStripMenuItem.Checked = false; fontToolStripMenuItem.Checked = false; } private void timesNewRomanToolStripMenuItem_Click(object sender, EventArgs e) { ClearFont(); timesNewRomanToolStripMenuItem.Checked = true; if (richTextBoxNoiDung.SelectedText.ToString() != "") { //Thay đổi font tại vị trí được tô đen richTextBoxNoiDung.SelectionFont = new Font("Times New Roman", richTextBoxNoiDung.Font.Size, richTextBoxNoiDung.Font.Style); } else richTextBoxNoiDung.Font= new Font("Times New Roman", richTextBoxNoiDung.Font.Size, richTextBoxNoiDung.Font.Style); }
ClearFont(); arialToolStripMenuItem.Checked = true; if (richTextBoxNoiDung.SelectedText.ToString() != "") { //Thay đổi font tại vị trí được tô đen richTextBoxNoiDung.SelectionFont = new Font("Arial", richTextBoxNoiDung.Font.Size, richTextBoxNoiDung.Font.Style); } else richTextBoxNoiDung.Font = new Font("Arial", richTextBoxNoiDung.Font.Size, richTextBoxNoiDung.Font.Style); }
private void courierToolStripMenuItem_Click(object sender, EventArgs e) { ClearFont(); courierToolStripMenuItem.Checked = true; if (richTextBoxNoiDung.SelectedText.ToString() != "") { //Thay đổi font tại vị trí được tô đen richTextBoxNoiDung.SelectionFont = new Font("Courier", richTextBoxNoiDung.Font.Size, richTextBoxNoiDung.Font.Style); } else richTextBoxNoiDung.Font = new Font("Courier", richTextBoxNoiDung.Font.Size, richTextBoxNoiDung.Font.Style); } private void fontToolStripMenuItem_Click(object sender, EventArgs e) { ClearFont(); fontToolStripMenuItem.Checked = true; FontDialog f = new FontDialog(); DialogResult result=f.ShowDialog(); if (result == DialogResult.Cancel) return; if (richTextBoxNoiDung.SelectedText.ToString() != "") richTextBoxNoiDung.SelectionFont = f.Font; else richTextBoxNoiDung.Font = f.Font; }
private void redToolStripMenuItem_Click(object sender, EventArgs e) { ClearColor(); redToolStripMenuItem.Checked = true; if (richTextBoxNoiDung.SelectedText.ToString() != "") { //Text được chọn có màu gì thì thay thế bằng màu Red richTextBoxNoiDung.SelectionColor = Color.Red; } else richTextBoxNoiDung.ForeColor = Color.Red; }
private void button_themnhieupt_Click(object sender, EventArgs e) { string s = ""; listBox1.Items.Clear(); s = textBox_nhapso.Text.ToString();
{ s = textBox_nhapso.Text.ToString(); string tmp = ""; int begin = 0; int dem = 0; for (int i = 0; i < s.Length; i++ ) if (s[i].ToString() == " ") { tmp = s.Substring(begin, dem); listBox1.Items.Add(tmp); dem = 0; begin = i+1; } else { dem++; } tmp = s.Substring(begin, dem); listBox1.Items.Add(tmp); } } private void button_xoalist_Click(object sender, EventArgs e) {
146
listBox1.Items.Clear(); }
private void button_chenpt_Click(object sender, EventArgs e) { string s = ""; s = textBox_nhapso.Text.ToString(); { listBox1.Items.Add(textBox_nhapso.Text); textBox_nhapso.Clear(); { for(int i=0;i<listBox1.Items.Count;i++) for (int j = i + 1; j < listBox1.Items.Count; j++) { int tmpi = int.Parse(listBox1.Items[i].ToString()); int tmpj = int.Parse(listBox1.Items[j].ToString()); if (tmpi > tmpj) { listBox1.Items[i] = tmpj; listBox1.Items[j] = tmpi; }
}
} } }
private void button_tangdan_Click(object sender, EventArgs e) { string s = ""; s = textBox_nhapso.Text.ToString(); { for(int i=0;i<listBox1.Items.Count;i++) for (int j = i + 1; j < listBox1.Items.Count; j++) { int tmpi = int.Parse(listBox1.Items[i].ToString()); int tmpj = int.Parse(listBox1.Items[j].ToString()); if (tmpi > tmpj) { listBox1.Items[i] = tmpj; listBox1.Items[j] = tmpi; } }
}
}
147
private void button_giamdan_Click(object sender, EventArgs e) { string s = ""; s = textBox_nhapso.Text.ToString(); { for(int i=0;i<listBox1.Items.Count;i++) for (int j = i + 1; j < listBox1.Items.Count; j++) { int tmpi = int.Parse(listBox1.Items[i].ToString()); int tmpj = int.Parse(listBox1.Items[j].ToString()); if (tmpi < tmpj) listBox1.Items[i] = tmpj; listBox1.Items[j] = tmpi;
} } } }
Mãng
public partial class frmArray_1 : Form { public frmArray_1() { InitializeComponent(); }
private void btnKQ_Click(object sender, EventArgs e) { int a = int.Parse(txtSoPtu.Text.Trim()); string b = mang(a); txtKQ.Text = b.Substring(0, b.Length - 1); } private string mang(int sopt)
148
{ string kq = ""; int[] mang = new int[sopt]; for (int i = 0; i < mang.Length; i++) { kq += Convert.ToString(i) + ";"; } return kq; } }
Cộng 3 phần từ trong mảng
public partial class frmArray_2 : Form { int[] mang; int so_nguyen = 0; object[] obj = new object[] { "Quy", 123, 1 }; public frmArray_2() { InitializeComponent(); }
{ //Khai báo & khởi tạo đối tượng lớp SUM Classes.clsSum cls = new CONTROLS.Classes.clsSum(); //Gán giá trị cho Filed cls.i = 15; cls.j = 20; //Lấy giá trị của Field MessageBox.Show("Tổng của " + cls.i.ToString() + " và " + cls.j.ToString() + " là " + cls.SUM().ToString()); }
{ case 0: kq = "Không"; break; case 1: kq = "Một"; break; case 2: kq = "Hai"; break; case 3: kq = "Ba"; break; case 4: kq = "Bốn"; break; case 5: kq = "Năm"; break; case 6: kq = "Sáu"; break; case 7: kq = "Bảy"; break; case 8: kq = "Tám"; break; case 9: kq = "Chín"; break; } return kq; } private string Doc_2_So(int so) { string kq = ""; int Hang_don_vi = Convert.ToInt16(so % 10); int Hang_chuc = Convert.ToInt16(so / 10);
//switch (so) //{ // case 0: kq = "Không"; break; // case 1: kq = "Một"; break; // case 2: kq = "Hai"; break; // case 3: kq = "Ba"; break; // case 4: kq = "Bốn"; break; // case 5: kq = "Năm"; break; // case 6: kq = "Sáu"; break; // case 7: kq = "Bảy"; break; // case 8: kq = "Tám"; break; // case 9: kq = "Chín"; break; //}
if (so >= 0 && so <= 9) kq = Doc_1_So(so); else if (so == 10) kq = "Mười"; else if (so == 15) kq = "Mười lăm"; else if (so >= 11 && so <= 19) kq = "Mười " + Doc_1_So(Hang_don_vi); else if (so == 20 || so == 30 || so == 40 || so == 50 || so == 60 || so == 70 || so == 80 || so == 90)
155
kq = Doc_1_So(Hang_chuc) + " mươi"; else if (so == 21 || so == 31 || so == 41 || so == 51 || so == 61 || so == 71 || so == 81 || so == 91) kq = Doc_1_So(Hang_chuc) + " mươi mốt"; else if (so == 25 || so == 35 || so == 45 || so == 55 || so == 65 || so == 75 || so == 85 || so == 95) kq = Doc_1_So(Hang_chuc) + " mươi lăm"; else kq = Doc_1_So(Hang_chuc) + " Mươi " + Doc_1_So(Hang_don_vi);
return kq; } }
Kéo Thả Mau tin
public partial class frmDragItem : Form { public frmDragItem() { InitializeComponent(); //this.lstItem1.MouseDown += new MouseEventHandler(lstItem1_MouseDown); //this.lstItem1.DragOver += new DragEventHandler(lstItem1_DragOver); //this.txt1.DragDrop += new DragEventHandler(txt1_DragDrop); ////this.txt2.DragDrop += new DragEventHandler(txt2_DragDrop); //this.txt1.DragEnter += new DragEventHandler(txt1_DragEnter); ////this.txt2.DragEnter += new DragEventHandler(txt2_DragEnter); txt1.AllowDrop = true; //cho phéo thả vào Textbox }
private void btnChonMau_Click(object sender, EventArgs e) { if (hop_mau.ShowDialog() == DialogResult.OK) { pen = new Pen(hop_mau.Color); //pen = new Pen( btnChonMau.BackColor = hop_mau.Color; } }
private void btnClose_MouseEnter(object sender, EventArgs e) { //MessageBox.Show("Nếu bạn nhấn nút này thì Form sẽ bị đóng", "Example: MouseEnter Event", MessageBoxButtons.OK, MessageBoxIcon.Information); label3.Text = "Nếu bạn nhấn nút này thì Form sẽ bị đóng"; }
frmTinhToan f = new frmTinhToan(); f.MdiParent = this; f.Show(); }
private void mnuCalculator_Click(object sender, EventArgs e) { frmCalculator f = new frmCalculator(); f.MdiParent = this; f.Show(); }
private void mnuDocSo_Click(object sender, EventArgs e) { frmDocSo f = new frmDocSo(); f.MdiParent = this; f.Show(); }
private void mnuDocHaiSo_Click(object sender, EventArgs e) { frmDoc_2_So f = new frmDoc_2_So(); f.MdiParent = this; f.Show(); }
private void mnuTongson_Click(object sender, EventArgs e) { frmTong_N_So f = new frmTong_N_So(); f.MdiParent = this; f.Show(); }
private void mnuToaDo_Click(object sender, EventArgs e) { frmToaDo f = new frmToaDo(); f.MdiParent = this; f.Show(); }
private void mnuDkControl_Click(object sender, EventArgs e) { frmDkControl f = new frmDkControl(); f.MdiParent = this; f.Show(); }
private void mnuQuaySo_Click(object sender, EventArgs e) { frmQuaySo f = new frmQuaySo();
172
f.MdiParent = this; f.Show(); }
private void mnuChonSinhVien_Click(object sender, EventArgs e) { frmChonSinhVien f = new frmChonSinhVien(); f.MdiParent = this; f.Show(); }
private void mnuChonNhieu_Click(object sender, EventArgs e) { frmChonNhieu f = new frmChonNhieu(); f.MdiParent = this; f.Show(); }
private void mnuTraiCay_Click(object sender, EventArgs e) { frmChonTraiCay f = new frmChonTraiCay(); f.MdiParent = this; f.Show(); }
private void mnuHelp_Click(object sender, EventArgs e) { MessageBox.Show("Sữa mẹ là tốt nhất cho sức khỏe & sự phát triển của trẻ sơ sinh và trẻ nhỏ", "Sữa", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); }
private void mnuXuLyChuoi_Click(object sender, EventArgs e) { frmXuLyChuoi f = new frmXuLyChuoi(); f.MdiParent = this; f.Show(); }
private void mnuMangNguyenTo_Click(object sender, EventArgs e) { frmMangSoNguyenTo f = new frmMangSoNguyenTo(); f.MdiParent = this; f.Show(); }
private void mnuXuLyHoTen_Click(object sender, EventArgs e) { frmXuLyHoTen f = new frmXuLyHoTen(); f.MdiParent = this; f.Show();
173
}
private void mnuDragItem_Click(object sender, EventArgs e) { frmDragItem f = new frmDragItem(); f.MdiParent = this; f.Show(); }
private void mnuMang1_Click(object sender, EventArgs e) { frmArray_1 f = new frmArray_1(); f.MdiParent = this; f.Show(); }
private void mnuMang2_Click(object sender, EventArgs e) { frmArray_2 f = new frmArray_2(); f.MdiParent = this; f.Show(); }
private void mnuCascade_Click(object sender, EventArgs e) { frmArray_2 f = new frmArray_2(); f.MdiParent = this; //f.Show(); f.LayoutMdi(MdiLayout.Cascade); }
private void btnCong_Click(object sender, EventArgs e) { a = float.Parse(txtSo1.Text.Trim()); b = float.Parse(txtSo2.Text.Trim()); kq = a + b; txtKQ.Text = kq.ToString(); }
private void btnTru_Click(object sender, EventArgs e) { a = float.Parse(txtSo1.Text.Trim()); b = float.Parse(txtSo2.Text.Trim()); kq = a - b; txtKQ.Text = kq.ToString();
180
}
private void btnNhan_Click(object sender, EventArgs e) { a = float.Parse(txtSo1.Text.Trim()); b = float.Parse(txtSo2.Text.Trim()); kq = a * b; txtKQ.Text = kq.ToString(); }
private void btnChia_Click(object sender, EventArgs e) { if (float.Parse(txtSo2.Text.Trim()) != 0) { a = float.Parse(txtSo1.Text.Trim()); b = float.Parse(txtSo2.Text.Trim()); kq = a / b; txtKQ.Text = kq.ToString(); } else MessageBox.Show("Không thể chia cho 0", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop); }
private void btnAnd_Click(object sender, EventArgs e) { int a = int.Parse(txtSo1.Text.Trim()); int b = int.Parse(txtSo2.Text.Trim()); txtKQ.Text = Convert.ToString(a & b); }
private void btnOr_Click(object sender, EventArgs e) { int a = int.Parse(txtSo1.Text.Trim()); int b = int.Parse(txtSo2.Text.Trim()); txtKQ.Text = Convert.ToString(a | b); }
private void btnDichTrai_Click(object sender, EventArgs e) { int a = int.Parse(txtSo1.Text.Trim()); int b = int.Parse(txtSo2.Text.Trim()); txtKQ.Text = Convert.ToString(a << b); }
private void btnDichPhai_Click(object sender, EventArgs e) { int a = int.Parse(txtSo1.Text.Trim()); int b = int.Parse(txtSo2.Text.Trim()); txtKQ.Text = Convert.ToString(a >> b);
181
} }
Toado
public partial class frmToaDo : Form { public frmToaDo() { InitializeComponent(); }
private void frmToaDo_MouseMove(object sender, MouseEventArgs e) { lblX.Text = "Tọa độ X : " + e.X.ToString(); lblY.Text = "Tọa độ Y : " + e.Y.ToString(); }
//Lớp trừu tượng (abstract) public abstract class clsAbstract { //Khai báo thuộc tính trừu tượng public abstract int Age { get; set; } public abstract string Name { get; //set; } public abstract string Address { //get; set; } }
public abstract class clsTruuTuong { public abstract string Path { get; set; } public abstract int NumberOfFiles { get; } //Khai báo phương thức trừu tượng
186
public abstract void Show(ListView lv); //Khai báo phương thức thường public void Show(ListView lsv, ComboBox cbo) { // } }
//Xây dựng lớp kế thừa từ lớp trừu tượng clsAbstract public class clsKeThua : clsAbstract { //Khai báo các biến thành viên private int mAge; public override int Age { get { return mAge; } set { mAge = value; } }
private string mName=""; public override string Name { get { return mName; } //set { mName = value; } }
//Xây dựng lớp kế thừa từ lớp trừu tượng clsTruuTuong public class clsPathFile : clsTruuTuong { //Khai báo các biến thành viên private string mPath; public override string Path { get { return mPath; } set { mPath = value; } }
private int mNumberOfFiles; public override int NumberOfFiles { get { return mNumberOfFiles; }
187
}
// public override void Show(ListView lv) { lv.Clear(); mNumberOfFiles = 0; ListViewItem lvi; foreach (string s in Directory.GetFiles(mPath)) { mNumberOfFiles += 1; lvi = new ListViewItem(mNumberOfFiles.ToString()); lvi.SubItems.Add(s); lv.Items.Add(lvi); } } }
class clsExample { void Use_clsCommon() { clsCommon exec = new clsCommon(); Console.WriteLine("Sum of i + j : {0}", exec.Sum()); Console.WriteLine("Multiple of i + j : {0}", exec.Multiple()); } //Khai báo 2 biến kiểu int int i = 10; int j = 20; //Method Sum public int sum() { return (i + j); } //Khai báo lớp lồng public class clsExampleOther1 { //Khai báo 2 biến kiểu int int a = 10; int b = 20; //Method Sum public int sum() { return (a + b); } } //Khai báo biến static static int k = 10; static int l = 20; //Khai báo lớp lồng public class clsExampleOther2
188
{ //Method Sum public int sum() { int ij = 0; //Khai báo & sử dụng lớp clsExample clsExample cls = new clsExample(); ij = cls.i + cls.j; return ij + k + l; } } }
partial class clsCommon { int i = 10; int j = 20; public int Sum() { return i + j; } }
partial class clsCommon { public int Multiple() { return i + j; } }
internal class clsInternal1 { int i = 1; int j = 2; internal int sum() { return (i + j); } }
public class clsProperty { //Khai báo biến cục bộ private int iValue; private int jValue; //Khai báo thuộc tính i, j public int i { get { return iValue;} set {iValue = value;} } //j public int j { get { return jValue; } set { jValue = value; } } //Khai báo method tính tổng 2 giá trị từ 2 thuộc tính i & j public int tong() { return (iValue + jValue); } }
public class clsPropertyReadOnly { //Khai báo thuộc tính cục bộ private string strPathValue; private int iNumberOfFiles;
190
private string sFileName=""; //Khai báo thuộc tính Path public string Path { get { return strPathValue; } set { strPathValue = value; } } //Thuộc tính chỉ đọc public int NumberOfFiles { get { return iNumberOfFiles; } } public string FileName { get { return sFileName; } } //Thuộc tính chỉ ghi (gán/Set) private string mPropertyName; public string PropertyName { //get { return mPropertyName; } set { mPropertyName = value; } } private int mValue; public int Value { //get { return mValue; } set { mValue = value; } } //Method public void Show(ListView lv) { iNumberOfFiles = 0; ListViewItem lvi; foreach (string s in Directory.GetFiles(strPathValue)) { iNumberOfFiles += 1; lvi = new ListViewItem(iNumberOfFiles.ToString()); lvi.SubItems.Add(s); lv.Items.Add(lvi); } } }
public class clsWriteOnly { //Khai báo biến cục bộ & thuộc tính chỉ đọc & gán private string mPathValue; public string PathValue {
191
//get { return mPathValue; } set { mPathValue = value; } } private int mNumberOfFiles; public int NumberOfFiles { get { return mNumberOfFiles; } //set { mNumberOfFiles = value; } }
//Method Show public void Show(ListView lv) { mNumberOfFiles = 0; ListViewItem lvi; foreach (string s in Directory.GetFiles(mPathValue)) { mNumberOfFiles += 1; lvi = new ListViewItem(mNumberOfFiles.ToString()); lvi.SubItems.Add(s); lv.Items.Add(lvi); } } } public class clsInfomation { private string mName; public string Name { get { return mName; } set { mName = value; } }
private string mAddress; public string Address { get { return mAddress; } set { mAddress = value; } }
private int mAge; public int Age { get { return mAge; } set { if (value > 100) mAge = 100; else if (value <= 0) mAge = 20; else
192
mAge = value; } } }
public static class clsInfomation1 { private static string mName; public static string Name { get { return mName; } set { mName = value; } }
private static string mAddress; public static string Address { get { return mAddress; } set { mAddress = value; } }
private static int mAge; public static int Age { get { return mAge; } set { if (value > 100) mAge = 100; else if (value <= 0) mAge = 20; else mAge = value; } } }
class clsParas { //Static public static short SInsOfCompany = 25; public static short MInsOfCompany = 3; public static short SInsOfEmployee = 5; public static short MInsOfEmployee = 2; //Non Static public float OT1 = 1.5F; public float OT2 = 1.8F; public float OT3 = 2.0F; public float OT4 = 2.5F; } class Chuong_trinh
193
{ public static void main(String[] args) { //truy cập các thuộc tính Static (ko cần khởi tạo lớp clsParas trước khi sử dụng) Console.WriteLine("Use Static Property :"); Console.WriteLine(clsParas.SInsOfCompany); Console.WriteLine(clsParas.SInsOfEmployee); Console.WriteLine(clsParas.MInsOfCompany); Console.WriteLine(clsParas.MInsOfEmployee); //truy cập các thuộc tính Non Static (ta cần khởi tạo lớp clsParas trước khi dùng) clsParas cls = new clsParas(); Console.WriteLine(cls.OT1); Console.WriteLine(cls.OT2); Console.WriteLine(cls.OT3); Console.WriteLine(cls.OT4); } }
public class clsSum { //Khai báo 2 Field public int i; public int j; //Khai báo phương thức public int SUM() { return (i + j); } } class clsTong { public int qty = 0; public int price = 0; //biến chỉ đọc public readonly float rate = 0.1F;