160 likes | 389 Views
Visual Programming. Lecture 4 Advanced Topics Devi, Erick, Reddy. Dynamic Component. Declaration. Declare dynamic component, an example: Create a button Button newBtn = new Button(); Create an array of to-be-filled-with-buttons Button[] newBtn = new Button[4];.
E N D
Visual Programming Lecture 4 Advanced Topics Devi, Erick, Reddy
Declaration • Declare dynamic component, an example: • Create a button Button newBtn = new Button(); • Create an array of to-be-filled-with-buttons Button[] newBtn = new Button[4];
Adding Buttons to Form • Set Properties: newBtn[0] = new Button(); newBtn[0].Text = "halo"; newBtn[0].Left = 0; this.Controls.Add(newBtn[0]);
Adding Events • Add event for dynamic component: newBtn[0].Click += new EventHandler(oke); void oke(object sender, EventArgs e) { Button xx= (Button) sender; MessageBox.Show(xx.Text ); }
Keyboard Events • Windows Forms provides two events that occur when a user presses a keyboard key and one event when a user releases a keyboard key: • The KeyDown event occurs once • The KeyPress event, which can occur multiple times when a user holds down the same key. • The KeyUp event occurs once when a user releases a key.
Keyboard Events public Form1() { InitializeComponent(); this.KeyPress += new KeyPressEventHandler(Form1_KeyPress); } private void Form1_KeyPress(object sender, KeyPressEventArgs e) { MessageBox.Show(e.KeyChar.ToString()); } UbahKeyPreviewmenjaditrue, agar event ditangkapoleh Form
Keyboard Events private void TextBox1_KeyDown(object sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.Up: //Do stuff break; case Keys.Down: //Do stuff break; case Keys.Left: //Do stuff break; case Keys.Right: //Do stuff break; } }
Random Random rnd = new Random(); • Create a number between 1 and 12 int month = rnd.Next(1, 13); • Create a number between 1 and 6 (inclusive) int dice = rnd.Next(1, 7); • Create a number between 0 and 51 (inclusive) int card = rnd.Next(52);
Timer • Starts raising the Elapsed event by setting Enabled to true. Timer1.Start • Gets or sets the interval at which to raise the Elapsed event. Timer1.Interval • Stops raising the Elapsed event by setting Enabled to false. Timer1.Stop
Create timer on the fly System.Timers.TimeraTimer= new System.Timers.Timer(); • Hook up the Elapsed event for the timer. aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); • Set the Interval to 2 seconds (2000 milliseconds). aTimer.Interval = 2000; aTimer.Enabled = true;
Exercise Make a simple Arkanoid Game using buttons like this figure: