-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));}
M. rit
  • 61
  • 6
  • 4
    Handling the key press would be a first step (http://stackoverflow.com/questions/3001237/how-to-catch-a-key-press-on-a-c-sharp-net-form). See if you can then call your method from that and, if not, post the updated code – keyboardP Jul 18 '16 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 – M. rit Jul 18 '16 at 18:18
  • 8
    Edit your question to add code. Do not add it in comments. – Jim Mischel Jul 18 '16 at 18:23

1 Answers1

-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!

Xephyr
  • 122
  • 1
  • 2
  • 9
  • 2
    Bad advice to use `CreateGraphics()`. It's volatile. Painting should _always_ be done in a proper `Paint` event. – DonBoitnott Jul 18 '16 at 18:46
  • @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. – Chris Dunaway Jul 18 '16 at 20:54