Don't
PictureBox
and, in most cases, don't use
SetPixel
. First one does not help you, only adds hassles and takes some extra resources and your development time, second one is prohibitively slow (but file if you want just to set one of few pixels). I'll tell you want to do.
I explained why not using
PictureBox
and what to do instead in my past answers:
Append a picture within picturebox[
^],
How do I clear a panel from old drawing[
^],
draw a rectangle in C#[
^].
And the problem with mouse position will be solved automatically: your mouse event argument instance (passed to your event handler) will give you the mouse position in the control's coordinate, as well as your graphics.
For further detail in image rendering, please see my past answers:
What kind of playful method is Paint? (DataGridViewImageCell.Paint(...))[
^],
capture the drawing on a panel[
^],
Drawing Lines between mdi child forms[
^],
see also:
How to speed up my vb.net application?[
^],
Zoom image in C# .net mouse wheel[
^].
You can actually use
SetPixel
, but only if you want to set one or just few, but this is almost never needed in practice. In all other cases, for reasonable performance, you need to use
LockBits
:
https://msdn.microsoft.com/en-us/library/system.drawing.bitmap.lockbits%28v=vs.110%29.aspx[
^].
You will find a code sample here:
https://msdn.microsoft.com/en-us/library/5ey6h79d(v=vs.110).aspx[
^].
—SA