I need some advice please on the best way to achieve a particular outcome...
My scenario...
I have a Form1 class, which is my main Form with a picture box on it.
I have a second class called camera that using an event handler grabs a frame (bitmap) from my webcam.
I then want to pass this frame to the picture box in the main form in the best fashion.
At the moment in the main form I have the code:
public static void setPB(Bitmap image)
{
var form = Form.ActiveForm as Form1;
form.pbWebCamDisplay = image;
}
then in the Camera class I use
Form1.setPB(currentFrame);
This works fine, however I wasn't sure if this was best programming practice? Is it possible t开发者_开发知识库o use custom events?
Thanks in advance for any help
Tom
I would create a method on the Camera class, which takes the picture and returns a Bitmap object.
So in the OnLoad or in the OnClick of a button, call that method and set the return value to the PictureBox...
var picture = new Camera().TakePicture();
myPictureBox.Image = picture;
Something like that :)
Edit: If the Camera class is an Event driven component (Camera.NewFrame event), try:
(in the constructor):
var camera = new Camera();
camera.OnNewFrame += new OnNewFrameEventHandler(MyEventHandler);
(event handler)
public void MyEnventHandler(EventArgs comingFromComponent)
{
var image = comingFromComponent.Frame; // (hopefully this is the case :))
myPictureBox.Image = image;
}
I would use events if I were in your place.
Yeah, I would say is perfectly good. You have a camera class that is in charge of handling the camera input and a public setter for a private member of your form. I would not change a bit.
That way you separate the different responsibilities for the functionalities into different classes. Don't handle the camera events inside the Form class, instead do as you're doing.
Definitely, events are the right choice. You can implement Observer Design Pattern using them. Your current implementation is not best practice - it forces tight coupling between Camera and Form class.
what drives the event that make Camera class grab the picture? This is important.
You don't even need the PictureBox setter in the form if the event is fired by the form itself.
BTW, i'm with Jorge Córdoba, a setter and a grab event are all that you need. Occam razor.
精彩评论