Click here to Skip to main content
13,202,706 members (57,752 online)
Rate this:
 
Please Sign up or sign in to vote.
Hello. I'm looking for the most ideal or practical method of streaming a live feed from a digital camera to a windows form (picture box) in .net while being able to control the camera settings programmatically.

Right now my method to connect is below.

First i'd like to mention that if there is a way to change settings while leaving the same camera connection in tact that would be great, but if there is a better method (like directShow?) i'm all for changing it too. I can't seem to get very good FPS or resolution out of this method and hopefully a new method or learning more about this method can resolve that issue too..

From Logitech they suggest using the IAMCameraControl and IAMVideoProcAmp but these are really old interfaces and there's not many good samples i could find.

My primary goal is changing the camera settings. If you have any advice or experience your thoughts would be appreciated. Thanks

Private Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal winHandle As Int32, ByVal wMsg As Int32, ByVal wParam As Int32, ByVal lParam As Int32) As Int32
Declare Function SetWindowPos Lib "user32.dll" Alias "SetWindowPos" (ByVal hwnd As IntPtr, ByVal hWndInsertAfter As IntPtr, ByVal x As Int32, ByVal y As Int32, ByVal cx As Int32, ByVal cy As Int32, ByVal wFlags As Integer) As Integer
Declare Function DestroyWindow Lib "user32.dll" (ByVal hndw As Integer) As Boolean
Declare Function capCreateCaptureWindowA Lib "avicap32.dll" (ByVal lpszWindowName As String, ByVal dwStyle As Int32, ByVal x As Int32, ByVal y As Int32, ByVal nWidth As Int32, ByVal nHeight As Int32, ByVal hWndParent As IntPtr, ByVal nID As Integer) As Integer


Private Sub OpenPreviewWindow()
    Try
        Dim iHeight As Integer = Me.PictureBox1.Height
        Dim iWidth As Integer = Me.PictureBox1.Width
        ' Open Preview window in picturebox .
        ' Create a child window with capCreateCaptureWindowA so you can display it in a picturebox.
        hHwnd = capCreateCaptureWindowA(iDevice.ToString, WS_VISIBLE Or WS_CHILD, 0, 0, Me.PictureBox1.Width, Me.PictureBox1.Height, Me.PictureBox1.Handle, 0)
        'connect to device
        If SendMessage(hHwnd, WM_CAP_DRIVER_CONNECT, iDevice, 0) Then
            'set preview scale
            SendMessage(hHwnd, WM_CAP_SET_SCALE, True, 0)
            'set preview rate in milliseconds
            SendMessage(hHwnd, WM_CAP_SET_PREVIEWRATE, 66, 0)
            'start previewing the image from the camera
            SendMessage(hHwnd, WM_CAP_SET_PREVIEW, True, 0)
            'resize window to fit in picturebox
            SetWindowPos(hHwnd, New IntPtr(HWND_BOTTOM), 0, 0, Me.PictureBox1.Width, Me.PictureBox1.Height, SWP_NOMOVE Or SWP_NOZORDER)
        Else
            DestroyWindow(hHwnd)
        End If
    Catch ex As Exception
        MsgBox("Error opening preview window (camera): " & ex.Message)
    End Try
End Sub
Posted 23-Oct-12 4:54am
RavonX366
Updated 23-Oct-12 4:57am
v2
Comments
Sergey Alexandrovich Kryukov 23-Oct-12 13:12pm
   
Whatever you do, don't use PictureBox, this is totally pointless.
--SA
RavonX 24-Oct-12 11:55am
   
pointless... ? your response is almost pointless buddy.

But moving toward something that isn't, how do you display the image you are receiving from the camera if not through a picture box?
Sergey Alexandrovich Kryukov 24-Oct-12 12:09pm
   
If you want to know what to use instead of PictureBox, I'll tell you, but if you want to argue -- no, thank you, please proceed on your own. PictureBox is only good to simplify static or almost always static picture presentation, everything else is presented by deriving from Control or some other classes... Simply put, PictureBox is almost never used, or used by the abusers...

--SA
RavonX 24-Oct-12 12:50pm
   
pointless. I don't really care if you don't help. I don't want to argue I'm here for DIGITAL CAMERAS LIKE THE FREAKIN TITLE WOULD IMPLY. and I might have a short fuse for jerk-offs.
Sergey Alexandrovich Kryukov 24-Oct-12 13:15pm
   
If you want to behave like that, nobody will want to help you. By saying all that, you don't look capable of using the advice, sorry. Not many will want to waste time for you, even though it could be false impression. I almost gave you the idea, but you are keeping to resist. It's up to you, of course.
--SA
RavonX 24-Oct-12 14:01pm
   
you know how I know you're a jerk off? Cause I asked

Quote "how do you display the image you are receiving from the camera if not through a picture box?"

before you said

Quote "If you want to know what to use instead of PictureBox, I'll tell you"

But you didn't. Quit trolling or say something more toward the point of this thread. Again *Title.
Sergey Alexandrovich Kryukov 24-Oct-12 15:18pm
   
OK, why do you think such rudeness can help you?

I started to help you, and not using a picture box is important part of it. First, you lie, no matter intentionally or not. I answered: "deriving from Control or some other classes". I did not elaborate only because you started to behave aggressively. Don't forget, I don't have problem showing video, you do...

Best of luck,
--SA
RavonX 24-Oct-12 15:39pm
   
now you call me a liar? you're a loser. the rudeness is because I see you wasting my time while you seemingly ask me to beg for an answer. Screw off.
Sergey Alexandrovich Kryukov 24-Oct-12 15:49pm
   
:-)
RavonX 24-Oct-12 14:23pm
   
Here's something more useful:
I'm exploring the DirectShowLib right now and finding more methods to work with a video feed. I can for sure manipulate the settings of the camera with IAMCameraControl after referencing DirectShowLib-2005 in the project and importing DirectShowLib to the form which makes it half the success.. now I'm searching for the way to stream video feed using directshow instead of using the avicap32 & can post the info when I get there if nothin else pops up between now and then.
Sergey Alexandrovich Kryukov 24-Oct-12 15:14pm
   
Of course. No one uses PictureBox, apparently -- you only argued about it, right?
--SA
RavonX 24-Oct-12 15:42pm
   
I'm not really sure what you're getting at here pal. But I think after the previous discussion perhaps you didn't read past the first paragraph of my question.

Because above, in the question, the initial post I do say
Quote "if there is a better method (like directShow?) i'm all for changing it too"
Sergey Alexandrovich Kryukov 24-Oct-12 15:59pm
   
I'm sorry. I just used the principle "You don't need to eat the whole egg to tell it's bad". As your first sentence has a critical flaw (PictureBox, indicated as a part of the goal, that's it), there is no need to go into further detail. Isn't that logical? There is a number of open-source codes showing the use of camera in Forms application...
--SA
RavonX 24-Oct-12 16:18pm
   
I couldn't read passed your first 2 words because I didn't believe they were true. I could smell the bad egg before I tasted it. Doesn't this follow your same logic?

Now yes, I lied, I read your whole response as I have done every time.

Thanks again for wasting more of my time friend.

I must admit that gem earlier about deriving controls, I did pick up on it and thank you for that. Also many of the open source solutions have a sample or dummy / simple camera control DLL attached that you must download and refer to. Some way too simple, some not so much but still lack some requirements like pan and tilt. This DirectShowLib seems to have everything I need and much more. It's one of the few I've seen to control all the settings on the Logitech Camera I'm using for these tests. As far as the picture box goes I could go edit it completely out of the first sentence, but I believe for someone who's serious about helping I don't think it'd deter an answer.
Sergey Alexandrovich Kryukov 24-Oct-12 16:29pm
   
:-) Don't get personal. Maybe cool down... that's better.
Instead of DirectShowLib, you could use directshow.net though: http://directshownet.sourceforge.net/
Besides, it depends on what you actually need. You could use available media control. I would advise using WFP instead where many things are much easier, but it depends on what "other things" you may need. WPF is itself based on DirectX (and very little related to Windows), but the use of it depends on your compatibility requirements (may be incompatible with code you already use and not available for Mono)...
--SA
Sergey Alexandrovich Kryukov 24-Oct-12 16:40pm
   
No. I told you that one of your statement was a lie. Either tell me it was not, or keep looking like you admit it. You see, I have nothing personal and try to keep to facts, but you seemingly boost your rage and getting into personal "characteristics". Those a foul way. And if you are saying things in rage, your mistakes are natural.
By the way, having no answers but mine is also not true ("you're the only one who's had an answer"). Will you get offended if I tell you the true name of such fact? Just be careful with such things.
--SA
RavonX 24-Oct-12 16:47pm
   
shoot no. I actually deleted both comments because you had gone back and edited one of yours with something nice and useful.
But just to let you know, my 2nd comment I deleted relented to the fact that no, someone else had indeed answered the other question and interestingly in the other question you and I didn't quite see things on the same terms either.
Sergey Alexandrovich Kryukov 24-Oct-12 16:53pm
   
Sorry, I don't know what are you talking about. I just looked at your 1st question and found Solution 1 and 2.
OK, have we discussed everything already? Perhaps we better draw a line...
Good luck,
--SA

P.S.: Ah, comments..? OK...
RavonX 24-Oct-12 17:06pm
   
With DirectShowLib which is the DLL from that DirectShowNet website I can adjust the settings programmatically (hue, brightness, pan, tilt, intensity..). it's an old one as I mention in the initial post, from 2005. I tested it along with the Avicap32.DLL streaming to a picturebox and it worked perfectly. Plus I think I found the graphing method that derives from a picturebox control and creates a video feed directly into the form.. more testing on that one tomorrow ^^

Once I get the final version I'll post a quicky of the code as an answer if there's nothing new.
Andy_dev 15-May-14 6:40am
   
RavonX did you ever complete the project - I have found nothing to help with controlling zoom and this article is the closest ! But the code you posted below isn't enough to get me any further as it's missing chunks of code I think. Please can you post your completed solution?
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

This is the option I'm running at the moment. This isn't ideal yet, and also not by any means finished. But it works.

First: download the DirectShowLibrary from <ahref>DirectShowNet[<ahref target="_blank" title="New Window">^]

Second: attach the DirectShowLib-2005 as a reference

Then the code:

Imports DirectShowLib
 
Public Class LEDTester2
 
    Private Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal winHandle As Int32, ByVal wMsg As Int32, ByVal wParam As Int32, ByVal lParam As Int32) As Int32
    Declare Function SetWindowPos Lib "user32.dll" Alias "SetWindowPos" (ByVal hwnd As IntPtr, ByVal hWndInsertAfter As IntPtr, ByVal x As Int32, ByVal y As Int32, ByVal cx As Int32, ByVal cy As Int32, ByVal wFlags As Integer) As Integer
    Declare Function DestroyWindow Lib "user32.dll" (ByVal hndw As Integer) As Boolean
    Declare Function capCreateCaptureWindowA Lib "avicap32.dll" (ByVal lpszWindowName As String, ByVal dwStyle As Int32, ByVal x As Int32, ByVal y As Int32, ByVal nWidth As Int32, ByVal nHeight As Int32, ByVal hWndParent As IntPtr, ByVal nID As Integer) As Integer
    Const WM_CAP_USER As Int32 = &H400
    Const WM_CAP_START As Int32 = WM_CAP_USER
    Const WM_CAP_DRIVER_CONNECT As Int32 = WM_CAP_START + 10
    Const WM_CAP_DRIVER_DISCONNECT As Int32 = WM_CAP_START + 11
    Const WM_CAP_EDIT_COPY As Int32 = WM_CAP_START + 30
    Const WM_CAP_SET_PREVIEW As Int32 = WM_CAP_START + 50
    Const WM_CAP_SET_PREVIEWRATE As Int32 = WM_CAP_START + 52
    Const WM_CAP_SET_SCALE As Int32 = WM_CAP_START + 53
    Const WS_CHILD As Int32 = &H40000000
    Const WS_VISIBLE As Int32 = &H10000000
    Const SWP_NOMOVE As Int32 = &H2S
    Const SWP_NOSIZE As Int32 = 1
    Const SWP_NOZORDER As Int32 = &H4S
    Const HWND_BOTTOM As Int32 = 1
    Dim iDevice As Integer = 0
    Dim hHwnd As Integer
    Dim capDevices As DsDevice()
    Dim camDevice As DsDevice = Nothing
    Dim camFilter As IBaseFilter = Nothing
    Dim camControl As IAMCameraControl
    Dim vidControl As IAMVideoProcAmp
    Dim camFound As Boolean = False
    Dim videoLoaded As Boolean = False
    Dim graphBuilder As IFilterGraph2 = CType(New FilterGraph, IFilterGraph2)
    Dim myZoomValue As Long = 0
    Dim myExposureValue As Long = 0
    Private cameraWaitTime As Integer = 250
    Public Enum SWP As UInt32
        NOSIZE = &H1
        NOMOVE = &H2
        NOZORDER = &H4
        NOREDRAW = &H8
        NOACTIVATE = &H10
        DRAWFRAME = &H20
        FRAMECHANGED = &H20
        SHOWWINDOW = &H40
        HIDEWINDOW = &H80
        NOCOPYBITS = &H100
        NOOWNERZORDER = &H200
        NOREPOSITION = &H200
        NOSENDCHANGING = &H400
        DEFERERASE = &H2000
        ASYNCWINDOWPOS = &H4000
    End Enum
 

    Private Sub OpenCamera()
 
        'open camera
 
        Try
            Dim iHeight As Integer = Me.PictureBox1.Height
            Dim iWidth As Integer = Me.PictureBox1.Width
            ' Open Preview window in picturebox .
            ' Create a child window with capCreateCaptureWindowA so you can display it in a picturebox.
            hHwnd = capCreateCaptureWindowA(iDevice.ToString, WS_VISIBLE Or WS_CHILD, 0, 0, Me.PictureBox1.Width, Me.PictureBox1.Height, Me.PictureBox1.Handle, 0)
            'connect to device
            If SendMessage(hHwnd, WM_CAP_DRIVER_CONNECT, iDevice, 0) Then
                'set preview scale
                SendMessage(hHwnd, WM_CAP_SET_SCALE, True, 0)
                'set preview rate in milliseconds
                SendMessage(hHwnd, WM_CAP_SET_PREVIEWRATE, 66, 0)
                'start previewing the image from the camera
                SendMessage(hHwnd, WM_CAP_SET_PREVIEW, True, 0)
                'resize window to fit in picturebox
                SetWindowPos(hHwnd, New IntPtr(HWND_BOTTOM), 0, 0, Me.PictureBox1.Width, Me.PictureBox1.Height, SWP_NOMOVE Or SWP_NOZORDER)
            Else
                DestroyWindow(hHwnd)
            End If
        Catch ex As Exception
            MsgBox("Error opening preview window (camera): " & ex.Message)
        End Try
 
        'control camera
 
        capDevices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice)
 
        For Each CD As DsDevice In capDevices
            If CD.Name = "USB2.0 2MP UVC AF Camera" Then
                camDevice = CD
                camFound = True
            ElseIf CD.Name = "Logitech HD Webcam C615" Then
                camDevice = CD
                camFound = True
            End If
        Next
 
        If camFound Then
            Dim hr As Integer = graphBuilder.AddSourceFilterForMoniker(camDevice.Mon, Nothing, camDevice.Name, camFilter)
            camControl = CType(camFilter, IAMCameraControl)
            vidControl = CType(camFilter, IAMVideoProcAmp)
 
            'Dim propSet As IKsPropertySet
            'propSet.Get()
 
            myZoomValue = 0
 
            Dim iMin As Integer
            Dim iMax As Integer
            Dim iStep As Integer
            Dim iDft As Integer
            Dim iResult As Integer
            'Dim iSetting As Integer
 
            iResult = camControl.GetRange(CameraControlProperty.Exposure, iMin, iMax, iStep, iDft, DirectShowLib.CameraControlFlags.Manual)
            iResult = camControl.Get(CameraControlProperty.Exposure, myExposureValue, DirectShowLib.CameraControlFlags.Manual)
            MsgBox("Exposure min-" & iMin.ToString & " Max-" & iMax.ToString & vbCrLf & "Current Setting: " & myExposureValue)
 
            videoLoaded = True
            MsgBox("Controlling camera")
        End If
    End Sub
 
    Private Sub LEDTester2_MouseWheel(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseWheel
        If videoLoaded Then
            'this is to play with settings, unfortunately Zoom was unavailable on the  cameras I used
            Dim iResult As Integer
 
            If e.Delta > 0 Then
                ''more exposure
                myExposureValue += 1
                If myExposureValue > -1 Then
                    myExposureValue = -1
                End If
                iResult = camControl.Set(CameraControlProperty.Exposure, myExposureValue, CameraControlFlags.Manual)
            Else
                ''less exposure
                myExposureValue -= 1
                If myExposureValue < -13 Then
                    myExposureValue = -13
                End If
                iResult = camControl.Set(CameraControlProperty.Exposure, myExposureValue, CameraControlFlags.Manual)
            End If
        End If
    End Sub
  Permalink  
v2
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

Update:

Here's a sample of the current code which uses video controls to build a video screen control on the form in the specified location with specified height and width. This also has a trackbar attached to the form along with a combobox to pick and edit settings for the camera view (gain, exposure, etc..).

It's pretty sweet. I haven't gone HD with it, and im not sure how to yet. That's one of the long term goals. I believe this is the start to getting there. Also I'm working on getting pictures out of this now as well. I'm thinking that will be pretty easy, though. We'll see!


Imports DirectShowLib
Imports System.Runtime.InteropServices
Imports System.Runtime.InteropServices.ComTypes
Imports System.Threading
Imports MySql.Data.MySqlClient


Inherits System.Windows.Forms.Form
'=----------------------------------------------------------------------
Dim myTestInt As Integer
Enum PlayState
    Stopped
    Paused
    Running
    Init
End Enum
Dim CurrentState As PlayState = PlayState.Stopped
Dim D As Integer = Convert.ToInt32("0X8000", 16)
Public WM_GRAPHNOTIFY As Integer = D + 1
Dim VideoWindow As IVideoWindow = Nothing
Dim MediaControl As IMediaControl = Nothing
Dim MediaEventEx As IMediaEventEx = Nothing
Dim GraphBuilder As IGraphBuilder = Nothing
Dim CaptureGraphBuilder As ICaptureGraphBuilder2 = Nothing
Dim rot As DsROTEntry = Nothing
Dim capDevices As DsDevice()
Dim camDevice As DsDevice = Nothing
Dim myExposureValue As Integer
Dim myBrightnessValue As Integer
Dim myGainValue As Integer
Dim mySaturationValue As Integer
Dim myZoomValue As Integer
Dim camFilter As IBaseFilter = Nothing
Dim camControl As IAMCameraControl
Dim vidControl As IAMVideoProcAmp
Dim myGraphBuilder As IFilterGraph2 = CType(New FilterGraph, IFilterGraph2)



#Region "Camera"
    Private Sub CaptureVideo()
        Dim hr As Integer = 0
        Dim sourceFilter As IBaseFilter = Nothing
        Try
            GetInterfaces()
            hr = Me.CaptureGraphBuilder.SetFiltergraph(Me.GraphBuilder) 'Specifies filter graph "graphbuilder" for the capture graph builder "captureGraphBuilder" to use.
            Debug.WriteLine("Attach the filter graph to the capture graph : " & DsError.GetErrorText(hr))
            DsError.ThrowExceptionForHR(hr)
            sourceFilter = FindCaptureDevice()
            SetConfigParms(CaptureGraphBuilder, sourceFilter, 45, 1280, 720)
            hr = Me.GraphBuilder.AddFilter(sourceFilter, "Video Capture")
            Debug.WriteLine("Add capture filter to our graph : " & DsError.GetErrorText(hr))
            DsError.ThrowExceptionForHR(hr)
            hr = Me.CaptureGraphBuilder.RenderStream(PinCategory.Capture, MediaType.Video, sourceFilter, Nothing, Nothing)
            Debug.WriteLine("Render the preview pin on the video capture filter : " & DsError.GetErrorText(hr))
            DsError.ThrowExceptionForHR(hr)
            Marshal.ReleaseComObject(sourceFilter)
            SetupVideoWindow()
            rot = New DsROTEntry(Me.GraphBuilder)
            hr = Me.MediaControl.Run()
            Debug.WriteLine("Start previewing video data : " & DsError.GetErrorText(hr))
            DsError.ThrowExceptionForHR(hr)
            Me.CurrentState = PlayState.Running
            Debug.WriteLine("The currentstate : " & Me.CurrentState.ToString)
        Catch ex As Exception
            MessageBox.Show("An unrecoverable error has occurred.With error : " & ex.ToString)
        End Try
    End Sub
    Private Sub SetConfigParms(ByVal capGraph As ICaptureGraphBuilder2, ByVal capFilter As IBaseFilter, ByVal iFrameRate As Integer, ByVal iWidth As Integer, ByVal iHeight As Integer)
        Try
            Dim hr As Integer
            Dim o As New Object
            Dim media As New AMMediaType
            Dim FoundFormat As Boolean
            ' Find the stream config interface
            hr = capGraph.FindInterface(PinCategory.Capture, MediaType.Video, capFilter, GetType(IAMStreamConfig).GUID, o)
            Dim videoStreamConfig As IAMStreamConfig = CType(o, IAMStreamConfig)
            If (videoStreamConfig Is Nothing) Then
                Throw New Exception("Failed to get IAMStreamConfig")
            End If
            'Dim myListOfResolution As New List(Of String)
            Dim iCount As Integer = 0, iSize As Integer = 0
            videoStreamConfig.GetNumberOfCapabilities(iCount, iSize)
            Dim pmtConfig As New AMMediaType
            For iFormat As Integer = 0 To iCount - 1
                Dim scc As New VideoStreamConfigCaps, pScc As IntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(scc))
                hr = videoStreamConfig.GetStreamCaps(iFormat, pmtConfig, pScc)
                DsError.ThrowExceptionForHR(hr)
                Marshal.PtrToStructure(pScc, scc)
                '' copy out the videoinfoheader
                Dim header As VideoInfoHeader = New VideoInfoHeader
                Marshal.PtrToStructure(pmtConfig.formatPtr, header)
                ''Examine the format, and possibly use it. 
                If pmtConfig.subType = MediaSubType.RGB24 Then
                    Debug.Print("iFormat: " & header.BmiHeader.Width & "x" & header.BmiHeader.Height)
                    'myListOfResolution.Add(header.BmiHeader.Width.ToString & " width, " & header.BmiHeader.Height.ToString & " height")
                    If header.BmiHeader.Width = iWidth And header.BmiHeader.Height = iHeight Then
                        If (iFrameRate > 0) Then
                            'header.AvgTimePerFrame = (10000000 / iFrameRate)
                        End If
                        hr = videoStreamConfig.SetFormat(pmtConfig)
                        DsError.ThrowExceptionForHR(hr)
                        FoundFormat = True
                        Exit For
                    End If
                End If
                ''Delete the media type when you are done.
                Marshal.DestroyStructure(pScc, GetType(VideoStreamConfigCaps))
                Marshal.DestroyStructure(pmtConfig.formatPtr, GetType(VideoInfoHeader))
                DsUtils.FreeAMMediaType(pmtConfig)
                pmtConfig = Nothing
                header = Nothing
                scc = Nothing
            Next
            If Not FoundFormat Then
                ' Get the existing format block
                hr = videoStreamConfig.GetFormat(media)
                DsError.ThrowExceptionForHR(hr)
                ' copy out the videoinfoheader
                Dim v As VideoInfoHeader = New VideoInfoHeader
                Marshal.PtrToStructure(media.formatPtr, v)
                ' if overriding the framerate, set the frame rate
                If (iFrameRate > 0) Then
                    v.AvgTimePerFrame = (10000000 / iFrameRate)
                End If
                ' if overriding the width, set the width
                If (iWidth > 0) Then
                    v.BmiHeader.Width = iWidth
                End If
                ' if overriding the Height, set the Height
                If (iHeight > 0) Then
                    v.BmiHeader.Height = iHeight
                End If
                ' Copy the media structure back
                Marshal.StructureToPtr(v, media.formatPtr, False)
                ' Set the new format
                hr = videoStreamConfig.SetFormat(media)
                DsError.ThrowExceptionForHR(hr)
                DsUtils.FreeAMMediaType(media)
                media = Nothing
            End If
        Catch ex As Exception
            MsgBox("error in setConfigParms - " & ex.Message)
        End Try
    End Sub
    Private Sub GetInterfaces()
        Dim hr As Integer = 0
        Me.GraphBuilder = CType(New FilterGraph, IGraphBuilder)
        Me.CaptureGraphBuilder = CType(New CaptureGraphBuilder2, ICaptureGraphBuilder2)
        Me.MediaControl = CType(Me.GraphBuilder, IMediaControl)
        Me.VideoWindow = CType(Me.GraphBuilder, IVideoWindow)
        Me.MediaEventEx = CType(Me.GraphBuilder, IMediaEventEx)
        hr = Me.MediaEventEx.SetNotifyWindow(Me.Handle, WM_GRAPHNOTIFY, IntPtr.Zero) 'This method designates a window as the recipient of messages generated by or sent to the current DirectShow object
        DsError.ThrowExceptionForHR(hr) 'ThrowExceptionForHR is a wrapper for Marshal.ThrowExceptionForHR, but additionally provides descriptions for any DirectShow specific error messages.If the hr value is not a fatal error, no exception will be thrown:
        Debug.WriteLine("I started Sub Get interfaces , the result is : " & DsError.GetErrorText(hr))
    End Sub
    Public Function FindCaptureDevice() As IBaseFilter
        Debug.WriteLine("Start the Sub FindCaptureDevice")
        Dim hr As Integer = 0
        Dim classEnum As IEnumMoniker = Nothing
        Dim moniker As IMoniker() = New IMoniker(0) {}
        Dim source As Object = Nothing
        Dim devEnum As ICreateDevEnum = CType(New CreateDevEnum, ICreateDevEnum)
        hr = devEnum.CreateClassEnumerator(FilterCategory.VideoInputDevice, classEnum, 0)
        Debug.WriteLine("Create an enumerator for the video capture devices : " & DsError.GetErrorText(hr))
        DsError.ThrowExceptionForHR(hr)
        Marshal.ReleaseComObject(devEnum)
        If classEnum Is Nothing Then
            Throw New ApplicationException("No video capture device was detected.\r\n\r\n" & _
                           "This sample requires a video capture device, such as a USB WebCam,\r\n" & _
                           "to be installed and working properly.  The sample will now close.")
        End If
        If classEnum.Next(moniker.Length, moniker, IntPtr.Zero) = 0 Then
            Dim iid As Guid = GetType(IBaseFilter).GUID
            moniker(0).BindToObject(Nothing, Nothing, iid, source)
        Else
            Throw New ApplicationException("Unable to access video capture device!")
        End If
        Marshal.ReleaseComObject(moniker(0))
        Marshal.ReleaseComObject(classEnum)
        Return CType(source, IBaseFilter)
    End Function
    Public Sub SetupVideoWindow()
        Dim hr As Integer = 0
        'set the video window to be a child of the main window
        'putowner : Sets the owning parent window for the video playback window. 
        hr = Me.VideoWindow.put_Owner(Me.Handle)
        DsError.ThrowExceptionForHR(hr)
        hr = Me.VideoWindow.put_WindowStyle(WindowStyle.Child Or WindowStyle.ClipChildren)
        DsError.ThrowExceptionForHR(hr)
        'Use helper function to position video window in client rect of main application window
        ResizeVideoWindow()
        'Make the video window visible, now that it is properly positioned
        'put_visible : This method changes the visibility of the video window. 
        hr = Me.VideoWindow.put_Visible(OABool.True)
        DsError.ThrowExceptionForHR(hr)
    End Sub
    Protected Overloads Sub WndProc(ByRef m As Message)
        Select Case m.Msg
            Case WM_GRAPHNOTIFY
                HandleGraphEvent()
        End Select
        If Not (Me.VideoWindow Is Nothing) Then
            Me.VideoWindow.NotifyOwnerMessage(m.HWnd, m.Msg, m.WParam.ToInt32, m.LParam.ToInt32)
        End If
        MyBase.WndProc(m)
    End Sub
    Public Sub HandleGraphEvent()
        Dim hr As Integer = 0
        Dim evCode As EventCode
        Dim evParam1 As Integer
        Dim evParam2 As Integer
        If Me.MediaEventEx Is Nothing Then
            Return
        End If
        While Me.MediaEventEx.GetEvent(evCode, evParam1, evParam2, 0) = 0
            '// Free event parameters to prevent memory leaks associated with
            '// event parameter data.  While this application is not interested
            '// in the received events, applications should always process them.
            hr = Me.MediaEventEx.FreeEventParams(evCode, evParam1, evParam2)
            DsError.ThrowExceptionForHR(hr)
            '// Insert event processing code here, if desired
        End While
    End Sub
    Public Sub closeinterfaces()
        '//stop previewing data
        If Not (Me.MediaControl Is Nothing) Then
            Me.MediaControl.StopWhenReady()
        End If
        Me.CurrentState = PlayState.Stopped
        '//stop recieving events
        If Not (Me.MediaEventEx Is Nothing) Then
            Me.MediaEventEx.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero)
        End If
        '// Relinquish ownership (IMPORTANT!) of the video window.
        '// Failing to call put_Owner can lead to assert failures within
        '// the video renderer, as it still assumes that it has a valid
        '// parent window.
        If Not (Me.VideoWindow Is Nothing) Then
            Me.VideoWindow.put_Visible(OABool.False)
            Me.VideoWindow.put_Owner(IntPtr.Zero)
        End If
        ' // Remove filter graph from the running object table
        If Not (rot Is Nothing) Then
            rot.Dispose()
            rot = Nothing
        End If
        '// Release DirectShow interfaces
        Marshal.ReleaseComObject(Me.MediaControl) : Me.MediaControl = Nothing
        Marshal.ReleaseComObject(Me.MediaEventEx) : Me.MediaEventEx = Nothing
        Marshal.ReleaseComObject(Me.VideoWindow) : Me.VideoWindow = Nothing
        Marshal.ReleaseComObject(Me.GraphBuilder) : Me.GraphBuilder = Nothing
        Marshal.ReleaseComObject(Me.CaptureGraphBuilder) : Me.CaptureGraphBuilder = Nothing
    End Sub
    Private Sub Form1_Resize1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
        If Me.WindowState = FormWindowState.Minimized Then
            ChangePreviewState(False)
        End If
        If Me.WindowState = FormWindowState.Normal Then
            ChangePreviewState(True)
        End If
        ResizeVideoWindow()
    End Sub
    Public Sub ChangePreviewState(ByVal showVideo As Boolean)
        Dim hr As Integer = 0
        '// If the media control interface isn't ready, don't call it
        If Me.MediaControl Is Nothing Then
            Debug.WriteLine("MediaControl is nothing")
            Return
        End If
        If showVideo = True Then
            If Not (Me.CurrentState = PlayState.Running) Then
                Debug.WriteLine("Start previewing video data")
                hr = Me.MediaControl.Run
                Me.CurrentState = PlayState.Running
            End If
        Else
            Debug.WriteLine("Stop previewing video data")
            hr = Me.MediaControl.StopWhenReady
            Me.CurrentState = PlayState.Stopped
        End If
    End Sub
    Public Sub ResizeVideoWindow()
        'Resize the video preview window to match owner window size
        'left , top , width , height
        If Not (Me.VideoWindow Is Nothing) Then 'if the videopreview is not nothing
            Me.VideoWindow.SetWindowPosition(0, 27, Me.Width, Me.ClientSize.Height - 27)
        End If
    End Sub
#End Region
 
#Region "Loading"
    Public Sub LoadMe(ByRef PartsDRow As DataRow, ByRef loadThisProjectRow As DataRow, ByVal editMode As Boolean)
        '_MyBKGDInfo1 = New myHelper
        'deletedItem = False
        '_myPartDRow = PartsDRow
        '_myProjectDRow = loadThisProjectRow
        InitializeBuffers()
        CaptureVideo()
        SetupCamera()
        If editMode Then
            'load info for trackbar / textboxes and show controls
            If camFound Then
                Me.Label1.Visible = True
                Me.TrackBar1.Visible = True
                Me.ComboBox1.Visible = True
                Me.ComboBox1.SelectedItem = Me.ComboBox1.Items(0)
            Else
                MsgBox("Camera not found")
                Me.Close()
                Exit Sub
            End If
        Else
            Me.Label1.Visible = False
            Me.TrackBar1.Visible = False
            Me.ComboBox1.Visible = False
        End If
        _WorkerPSU.RunWorkerAsync()
        Me.Show()
    End Sub
    Private Sub SetupCamera()
        'open camera
        If Not camFound Then
            capDevices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice)
            For Each CD As DsDevice In capDevices
                If CD.Name = "USB2.0 2MP UVC AF Camera" Then
                    camDevice = CD
                    camFound = True
                ElseIf CD.Name = "Logitech HD Webcam C615" Then
                    camDevice = CD
                    camFound = True
                End If
            Next
        End If
        If camFound Then
            Dim hr As Integer = myGraphBuilder.AddSourceFilterForMoniker(camDevice.Mon, Nothing, camDevice.Name, camFilter)
            camControl = CType(camFilter, IAMCameraControl)
            vidControl = CType(camFilter, IAMVideoProcAmp)
 
            Dim iMin As Integer
            Dim iMax As Integer
            Dim iStep As Integer
            Dim iDft As Integer
            Dim iResult As Integer
 
            iResult = camControl.GetRange(CameraControlProperty.Exposure, iMin, iMax, iStep, iDft, DirectShowLib.CameraControlFlags.Manual)
            'If DBNull.Value.Equals(_myProjectDRow.Item(3)) Then
            myExposureValue = 0.35 * iMax
            'Else
            '    myExposureValue = _myProjectDRow.Item(3)
            'End If
            iResult = camControl.Set(CameraControlProperty.Exposure, myExposureValue, DirectShowLib.CameraControlFlags.Manual)
            Me.ComboBox1.Items.Add("Exposure")
 
            iResult = camControl.GetRange(CameraControlProperty.Focus, iMin, iMax, iStep, iDft, DirectShowLib.CameraControlFlags.Manual)
            iResult = camControl.Set(CameraControlProperty.Focus, 0, DirectShowLib.CameraControlFlags.Manual)
 
            iResult = camControl.GetRange(CameraControlProperty.Pan, iMin, iMax, iStep, iDft, DirectShowLib.CameraControlFlags.Manual)
            iResult = camControl.Set(CameraControlProperty.Pan, 0, DirectShowLib.CameraControlFlags.Manual)
 

 

            'zoom doesn't work very well on logitech c615 model
 
            'iResult = camControl.Get(CameraControlProperty.Zoom, myZoomValue, CameraControlFlags.Manual)
            'MsgBox("my zoom value = " & myZoomValue.ToString & vbCrLf & "iresult = " & iResult.ToString)
 
            iResult = camControl.GetRange(CameraControlProperty.Zoom, iMin, iMax, iStep, iDft, DirectShowLib.CameraControlFlags.Manual)
            'If DBNull.Value.Equals(_myProjectDRow.Item(3)) Then
            myZoomValue = iMin
            'Else
            '    myExposureValue = _myProjectDRow.Item( ????? )
            'End If
            iResult = camControl.Set(CameraControlProperty.Zoom, myZoomValue, DirectShowLib.CameraControlFlags.Manual)
            Me.ComboBox1.Items.Add("Zoom")
            Me.Button1.Text = "Zoom in"
 

 

            iResult = vidControl.GetRange(VideoProcAmpProperty.BacklightCompensation, iMin, iMax, iStep, iDft, DirectShowLib.VideoProcAmpFlags.Manual)
            iResult = vidControl.Set(VideoProcAmpProperty.BacklightCompensation, iMax, DirectShowLib.VideoProcAmpFlags.Manual)
 
            iResult = vidControl.GetRange(VideoProcAmpProperty.Brightness, iMin, iMax, iStep, iDft, DirectShowLib.VideoProcAmpFlags.Manual)
            'If DBNull.Value.Equals(_myProjectDRow.Item(4)) Then
            myBrightnessValue = 0.15 * iMax
            'Else
            '    myBrightnessValue = _myProjectDRow.Item(4)
            'End If
            iResult = vidControl.Set(VideoProcAmpProperty.Brightness, myBrightnessValue, DirectShowLib.VideoProcAmpFlags.Manual)
            Me.ComboBox1.Items.Add("Brightness")
 
            iResult = vidControl.GetRange(VideoProcAmpProperty.Contrast, iMin, iMax, iStep, iDft, DirectShowLib.VideoProcAmpFlags.Manual)
            iResult = vidControl.Set(VideoProcAmpProperty.Contrast, iMax, DirectShowLib.VideoProcAmpFlags.Manual)
 
            iResult = vidControl.GetRange(VideoProcAmpProperty.Gain, iMin, iMax, iStep, iDft, DirectShowLib.VideoProcAmpFlags.Manual)
            'If DBNull.Value.Equals(_myProjectDRow.Item(5)) Then
            myGainValue = 0.25 * iMax
            '    myGainValue = 0
            'Else
            '    myGainValue = _myProjectDRow.Item(5)
            'End If
            iResult = vidControl.Set(VideoProcAmpProperty.Gain, myGainValue, DirectShowLib.VideoProcAmpFlags.Manual)
            Me.ComboBox1.Items.Add("Gain")
 
            iResult = vidControl.GetRange(VideoProcAmpProperty.Saturation, iMin, iMax, iStep, iDft, DirectShowLib.VideoProcAmpFlags.Manual)
            'If DBNull.Value.Equals(_myProjectDRow.Item(6)) Then
            mySaturationValue = 0.3 * iMax
            'Else
            '    mySaturationValue = _myProjectDRow.Item(6)
            'End If
            iResult = vidControl.Set(VideoProcAmpProperty.Saturation, mySaturationValue, DirectShowLib.VideoProcAmpFlags.Manual)
            Me.ComboBox1.Items.Add("Saturation")
 
            iResult = vidControl.GetRange(VideoProcAmpProperty.Sharpness, iMin, iMax, iStep, iDft, DirectShowLib.VideoProcAmpFlags.Manual)
            iResult = vidControl.Set(VideoProcAmpProperty.Sharpness, iMax, DirectShowLib.VideoProcAmpFlags.Manual)
 
            iResult = vidControl.GetRange(VideoProcAmpProperty.WhiteBalance, iMin, iMax, iStep, iDft, DirectShowLib.VideoProcAmpFlags.Manual)
            iResult = vidControl.Set(VideoProcAmpProperty.WhiteBalance, iMax, DirectShowLib.VideoProcAmpFlags.Manual)
 
            videoLoaded = True
        End If
    End Sub
    Private Sub ComboBox1_SelectedIndexChanged1(sender As Object, e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
        Me.Focus()
        AttachItemToTrackBar()
    End Sub
    Private Sub AttachItemToTrackBar()
        If videoLoaded Then
            'Dim iResult As Integer
            Dim iSetting As Integer = GetCurrentSetting()
            Dim iMin As Integer
            Dim iMax As Integer
            GetMinMaxSetting(iMin, iMax)
            Me.TrackBar1.Minimum = iMin
            Me.TrackBar1.Maximum = iMax
            Me.TrackBar1.Value = iSetting
            SetTextBoxToTrackBar()
        End If
    End Sub
    Private Sub TrackBar1_Scroll(sender As System.Object, e As System.EventArgs) Handles TrackBar1.Scroll
        SetCurrentSetting(Me.TrackBar1.Value)
        SetTextBoxToTrackBar()
    End Sub
    Private Sub SetTextBoxToTrackBar()
        Me.Label1.Text = Me.TrackBar1.Value
    End Sub
    Private Sub GetMinMaxSetting(ByRef minVal As Integer, ByRef maxVal As Integer)
        Dim iResult As Integer
        Dim iStep As Integer
        Dim iDft As Integer
        Select Case Me.ComboBox1.SelectedItem
            Case "Zoom"
                iResult = camControl.GetRange(CameraControlProperty.Zoom, minVal, maxVal, iStep, iDft, DirectShowLib.CameraControlFlags.Manual)
            Case "Exposure"
                iResult = camControl.GetRange(CameraControlProperty.Exposure, minVal, maxVal, iStep, iDft, DirectShowLib.CameraControlFlags.Manual)
            Case "Focus"
                iResult = camControl.GetRange(CameraControlProperty.Focus, minVal, maxVal, iStep, iDft, DirectShowLib.CameraControlFlags.Manual)
            Case "Iris"
                iResult = camControl.GetRange(CameraControlProperty.Iris, minVal, maxVal, iStep, iDft, DirectShowLib.CameraControlFlags.Manual)
            Case "Pan"
                iResult = camControl.GetRange(CameraControlProperty.Pan, minVal, maxVal, iStep, iDft, DirectShowLib.CameraControlFlags.Manual)
            Case "Roll"
                iResult = camControl.GetRange(CameraControlProperty.Roll, minVal, maxVal, iStep, iDft, DirectShowLib.CameraControlFlags.Manual)
            Case "Tilt"
                iResult = camControl.GetRange(CameraControlProperty.Tilt, minVal, maxVal, iStep, iDft, DirectShowLib.CameraControlFlags.Manual)
            Case "Zoom"
                iResult = camControl.GetRange(CameraControlProperty.Zoom, minVal, maxVal, iStep, iDft, DirectShowLib.CameraControlFlags.Manual)
            Case "BacklightCompensation"
                iResult = vidControl.GetRange(VideoProcAmpProperty.BacklightCompensation, minVal, maxVal, iStep, iDft, DirectShowLib.VideoProcAmpFlags.Manual)
            Case "Brightness"
                iResult = vidControl.GetRange(VideoProcAmpProperty.Brightness, minVal, maxVal, iStep, iDft, DirectShowLib.VideoProcAmpFlags.Manual)
            Case "ColorEnable"
                iResult = vidControl.GetRange(VideoProcAmpProperty.ColorEnable, minVal, maxVal, iStep, iDft, DirectShowLib.VideoProcAmpFlags.Manual)
            Case "Contrast"
                iResult = vidControl.GetRange(VideoProcAmpProperty.Contrast, minVal, maxVal, iStep, iDft, DirectShowLib.VideoProcAmpFlags.Manual)
            Case "Gain"
                iResult = vidControl.GetRange(VideoProcAmpProperty.Gain, minVal, maxVal, iStep, iDft, DirectShowLib.VideoProcAmpFlags.Manual)
            Case "Gamma"
                iResult = vidControl.GetRange(VideoProcAmpProperty.Gamma, minVal, maxVal, iStep, iDft, DirectShowLib.VideoProcAmpFlags.Manual)
            Case "Hue"
                iResult = vidControl.GetRange(VideoProcAmpProperty.Hue, minVal, maxVal, iStep, iDft, DirectShowLib.VideoProcAmpFlags.Manual)
            Case "Saturation"
                iResult = vidControl.GetRange(VideoProcAmpProperty.Saturation, minVal, maxVal, iStep, iDft, DirectShowLib.VideoProcAmpFlags.Manual)
            Case "Sharpness"
                iResult = vidControl.GetRange(VideoProcAmpProperty.Sharpness, minVal, maxVal, iStep, iDft, DirectShowLib.VideoProcAmpFlags.Manual)
            Case "WhiteBalance"
                iResult = vidControl.GetRange(VideoProcAmpProperty.WhiteBalance, minVal, maxVal, iStep, iDft, DirectShowLib.VideoProcAmpFlags.Manual)
        End Select
    End Sub
    Private Function GetCurrentSetting() As Integer
        Dim iResult As Integer
        Dim iSetting As Double
        Select Case Me.ComboBox1.SelectedItem
            Case "Zoom"
                iResult = camControl.Get(CameraControlProperty.Zoom, iSetting, DirectShowLib.CameraControlFlags.Manual)
            Case "Exposure"
                iResult = camControl.Get(CameraControlProperty.Exposure, iSetting, DirectShowLib.CameraControlFlags.Manual)
            Case "Focus"
                iResult = camControl.Get(CameraControlProperty.Focus, iSetting, DirectShowLib.CameraControlFlags.Manual)
            Case "Iris"
                iResult = camControl.Get(CameraControlProperty.Iris, iSetting, DirectShowLib.CameraControlFlags.Manual)
            Case "Pan"
                iResult = camControl.Get(CameraControlProperty.Pan, iSetting, DirectShowLib.CameraControlFlags.Manual)
            Case "Roll"
                iResult = camControl.Get(CameraControlProperty.Roll, iSetting, DirectShowLib.CameraControlFlags.Manual)
            Case "Tilt"
                iResult = camControl.Get(CameraControlProperty.Tilt, iSetting, DirectShowLib.CameraControlFlags.Manual)
            Case "Zoom"
                iResult = camControl.Get(CameraControlProperty.Zoom, iSetting, DirectShowLib.CameraControlFlags.Manual)
            Case "BacklightCompensation"
                iResult = vidControl.Get(VideoProcAmpProperty.BacklightCompensation, iSetting, DirectShowLib.CameraControlFlags.Manual)
            Case "Brightness"
                iResult = vidControl.Get(VideoProcAmpProperty.Brightness, iSetting, DirectShowLib.CameraControlFlags.Manual)
            Case "ColorEnable"
                iResult = vidControl.Get(VideoProcAmpProperty.ColorEnable, iSetting, DirectShowLib.CameraControlFlags.Manual)
            Case "Contrast"
                iResult = vidControl.Get(VideoProcAmpProperty.Contrast, iSetting, DirectShowLib.CameraControlFlags.Manual)
            Case "Gain"
                iResult = vidControl.Get(VideoProcAmpProperty.Gain, iSetting, DirectShowLib.CameraControlFlags.Manual)
            Case "Gamma"
                iResult = vidControl.Get(VideoProcAmpProperty.Gamma, iSetting, DirectShowLib.CameraControlFlags.Manual)
            Case "Hue"
                iResult = vidControl.Get(VideoProcAmpProperty.Hue, iSetting, DirectShowLib.CameraControlFlags.Manual)
            Case "Saturation"
                iResult = vidControl.Get(VideoProcAmpProperty.Saturation, iSetting, DirectShowLib.CameraControlFlags.Manual)
            Case "Sharpness"
                iResult = vidControl.Get(VideoProcAmpProperty.Sharpness, iSetting, DirectShowLib.CameraControlFlags.Manual)
            Case "WhiteBalance"
                iResult = vidControl.Get(VideoProcAmpProperty.WhiteBalance, iSetting, DirectShowLib.CameraControlFlags.Manual)
        End Select
        Return iSetting
    End Function
    Private Sub SetCurrentSetting(ByVal newValue As Integer)
        Dim iResult As Integer
        Select Case Me.ComboBox1.SelectedItem
            Case "Zoom"
                iResult = camControl.Set(CameraControlProperty.Zoom, newValue, DirectShowLib.CameraControlFlags.Manual)
                myZoomValue = newValue
            Case "Exposure"
                iResult = camControl.Set(CameraControlProperty.Exposure, newValue, DirectShowLib.CameraControlFlags.Manual)
                myExposureValue = newValue
            Case "Brightness"
                iResult = vidControl.Set(VideoProcAmpProperty.Brightness, newValue, DirectShowLib.VideoProcAmpFlags.Manual)
                myBrightnessValue = newValue
            Case "Gain"
                iResult = vidControl.Set(VideoProcAmpProperty.Gain, newValue, DirectShowLib.VideoProcAmpFlags.Manual)
                myGainValue = newValue
            Case "Saturation"
                iResult = vidControl.Set(VideoProcAmpProperty.Saturation, newValue, DirectShowLib.VideoProcAmpFlags.Manual)
                mySaturationValue = newValue
        End Select
    End Sub
  Permalink  
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy |
Web03 | 2.8.171020.1 | Last Updated 16 May 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100