-2

I wanted to draw a pixel on a specific place in my form when I press a specific key in my keyboard. how can I do that? here's a snippet code from my project:

 private void paint(object sender, PaintEventArgs e) { int x = 5, y = 5; e.Graphics.FillRectangle(Brushes.Black, new Rectangle(55, 55, x, y));} 
3
  • 4
    Handling the key press would be a first step (stackoverflow.com/questions/3001237/…). See if you can then call your method from that and, if not, post the updated code Commented Jul 18, 2016 at 18:12
  • this is the code i am working on: 'private void press(object sender, KeyEventArgs e, PaintEventArgs g) int x = 5, y = 5; if (e.KeyValue <'a' && e.KeyValue <= 'z'){ MessageBox.Show("Form.KeyPress: '" + e.KeyValue.ToString() + "' pressed."); switch (e.KeyValue) { case (char) 'a': g.Graphics.FillRectangle(Brushes.Black, new Rectangle(55, 55, x, y)); break; case (char)'b': case (char)'c': MessageBox.Show("Form.KeyPress: '" + e.KeyValue.ToString() + "' consumed."); e.Handled = true; break; } }' @keyboardP Commented Jul 18, 2016 at 18:18
  • 8
    Edit your question to add code. Do not add it in comments. Commented Jul 18, 2016 at 18:23

1 Answer 1

-1

I'm a little rusty to winforms, but I think you should try this:

  1. Select the main form, go to the properties window, go to the events part of the properties window, and click "KeyDown."

  2. In the KeyDown method, put in this:

     if (e.KeyCode == Keys.A) { Graphics g = this.CreateGraphics(); Pen pen = new Pen(Color.Black, 2); Brush brush = Brushes.Black; int x = 5; int y = 5; g.FillRectangle(brush, x, y, 55, 55); } 

VOILA!

Sign up to request clarification or add additional context in comments.

2 Comments

Bad advice to use CreateGraphics(). It's volatile. Painting should always be done in a proper Paint event.
@DonBoitnott is right. Anything drawn with this method will be erased if the form is repainted or if a window crosses in front of it. Also, the Graphics instance you get from CreateGraphics may not be the same as the one you get in the OnPaint override. The on in OnPaint might different if the form is double buffered, for example.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.