HRESULT WIACamera::GetDeviceProperty(const unsigned int CamID, const PropertyType Type, int *piValue)
{
	HRESULT hr = S_OK;
	if ( CamID >= m_iCount ) return S_FALSE;

	IWiaPropertyStorage *pWiaPropertyStorage;
	hr = m_vRootItem[CamID]->QueryInterface(IID_IWiaPropertyStorage,(void**)&pWiaPropertyStorage);
	if (hr != S_OK) {
		return E_NOINTERFACE;
	}

	PROPSPEC PropSpec;
	PROPVARIANT PropVar;
	PropSpec.ulKind = PRSPEC_PROPID;

	if ( Type==CAMERA_SHUTTERSPEED ) {
		PropSpec.propid = WIA_DPC_EXPOSURE_TIME;
		hr = pWiaPropertyStorage->ReadMultiple( 1, &PropSpec, &PropVar );
	} else if ( Type==CAMERA_GAIN ) {
		PropSpec.propid = WIA_DPC_EXPOSURE_INDEX;
		hr = pWiaPropertyStorage->ReadMultiple( 1, &PropSpec, &PropVar );
	} else if ( Type==CAMERA_APERTURE ) {
		PropSpec.propid = WIA_DPC_FNUMBER;
		hr = pWiaPropertyStorage->ReadMultiple( 1, &PropSpec, &PropVar );
	} else {
		hr = E_NOTIMPL;
	}

	if (pWiaPropertyStorage) {
		pWiaPropertyStorage->Release();
		pWiaPropertyStorage = NULL;
	}
	if (hr == S_OK) {
		*piValue = (int)PropVar.lVal;
	}

	return hr;
}
HRESULT PrintItemName( IWiaItem *pWiaItem )
{
    //
    // Validate arguments
    //
    if (NULL == pWiaItem)
    {
        return E_INVALIDARG;
    }

    //
    // Get the IWiaPropertyStorage interface
    //
    IWiaPropertyStorage *pWiaPropertyStorage = NULL;
    HRESULT hr = pWiaItem->QueryInterface( IID_IWiaPropertyStorage, (void**)&pWiaPropertyStorage );
    if (SUCCEEDED(hr))
    {
        //
        // Declare PROPSPECs and PROPVARIANTs, and initialize them to zero.
        //
        PROPSPEC PropSpec[1] = {0};
        PROPVARIANT PropVar[1] = {0};

        //
        // How many properties are we querying for?
        //
        const ULONG c_nPropertyCount = sizeof(PropSpec)/sizeof(PropSpec[0]);

        //
        // Define which properties we want to read:
        // Device ID.  This is what we'd use to create
        // the device.
        //
        PropSpec[0].ulKind = PRSPEC_PROPID;
        PropSpec[0].propid = WIA_IPA_FULL_ITEM_NAME;

        //
        // Ask for the property values
        //
        hr = pWiaPropertyStorage->ReadMultiple( c_nPropertyCount, PropSpec, PropVar );
        if (SUCCEEDED(hr))
        {
            //
            // IWiaPropertyStorage::ReadMultiple will return S_FALSE if some
            // properties could not be read, so we have to check the return
            // types for each requested item.
            //
            
            //
            // Check the return type for the device ID
            //
            if (VT_BSTR == PropVar[0].vt)
            {
                //
                // Do something with the device ID
                //
                _tprintf( TEXT("Item Name: %ws\n"), PropVar[0].bstrVal );
            }

            //
            // Free the returned PROPVARIANTs
            //
            FreePropVariantArray( c_nPropertyCount, PropVar );
        }
        else
        {
            ReportError( TEXT("Error calling IWiaPropertyStorage::ReadMultiple"), hr );
        }

        //
        // Release the IWiaPropertyStorage interface
        //
        pWiaPropertyStorage->Release();
        pWiaPropertyStorage = NULL;
    }

    //
    // Return the result of reading the properties
    //
    return hr;
}
HRESULT WIACamera::VideoCameraCapture(IWiaItem* pIWiaRoot, IplImage** ppIplImage)
{
	static int COUNTER = 0;
	COUNTER++;
	HRESULT hr = S_OK;
	if (pIWiaRoot==NULL) {
		cvReleaseImage(ppIplImage);
		(*ppIplImage) = NULL;
		return hr;
	}

	IWiaPropertyStorage *pIWiaPropStg	= NULL;
	// Get the next WIA device
	hr = pIWiaRoot->QueryInterface(IID_IWiaPropertyStorage,(void**)&pIWiaPropStg);

	if (SUCCEEDED(hr))	{
		// Get the device type of the device
		PROPSPEC    PropSpec[3];
		PROPVARIANT PropVar[3];
		memset(PropVar,0,sizeof(PropVar));
		PropSpec[0].ulKind = PRSPEC_PROPID;
		PropSpec[0].propid = WIA_DIP_DEV_ID;
		PropSpec[1].ulKind = PRSPEC_PROPID;
		PropSpec[1].propid = WIA_DIP_DEV_TYPE;
		PropSpec[2].ulKind = PRSPEC_PROPID;
		PropSpec[2].propid = WIA_DPV_IMAGES_DIRECTORY;
		// Get the type and the ID of each device
		hr = pIWiaPropStg->ReadMultiple(sizeof(PropSpec)/sizeof(PROPSPEC),
										PropSpec, PropVar);
		WORD myDev = GET_STIDEVICE_TYPE(PropVar[1].lVal);
		if (SUCCEEDED(hr)) {
			hr = m_pWiaVideo->put_ImagesDirectory(PropVar[2].bstrVal);
	    }
		if (SUCCEEDED(hr)) {
	        hr = m_pWiaVideo->put_PreviewVisible(FALSE);
			hr = m_pWiaVideo->CreateVideoByWiaDevID(PropVar[0].bstrVal, NULL, FALSE, TRUE);
	    }
	}
    //
    // Take a picture.  When this function returns, WIA Video will have already
    // captured a still image from the video stream, and it saved the image in
    // the 'FileName' file.
    //
	BSTR bstrFileName = NULL;

    if (SUCCEEDED(hr))
    {
		Sleep(2000);
		hr = m_pWiaVideo->TakePicture(&bstrFileName);
    }

    if (SUCCEEDED(hr))
    {
		cvReleaseImage(ppIplImage);
		// Convert to a char*
		const int BUFFER_SIZE = 4096;
		char filepath[BUFFER_SIZE];
		_bstr_t bstrIntermediate(bstrFileName);    // convert to
												// _bstr_t
		// you have to go through _bstr_t to have it work in ANSI
		// and Unicode
		sprintf_s(filepath, BUFFER_SIZE, "%s", (LPCTSTR)bstrIntermediate);
		(*ppIplImage) = cvLoadImage((char*)filepath);
	}
	return hr;
}
HRESULT WIACamera::Initialize()
{
	// CoInitialize(NULL);
	CoInitializeEx(NULL, COINIT_MULTITHREADED);

    IEnumWIA_DEV_INFO   *pWiaEnumDevInfo    = NULL;
	
	//
    // Create an instance of the device manager
    //
	HRESULT hr = CoCreateInstance( CLSID_WiaDevMgr, NULL, CLSCTX_LOCAL_SERVER, IID_IWiaDevMgr, (void**)&m_pWiaDevMgr );
    hr = CoCreateInstance(CLSID_WiaVideo, NULL, CLSCTX_INPROC_SERVER, IID_IWiaVideo, (void**) &m_pWiaVideo);

	if (SUCCEEDED(hr)) {
		//
		// Enumerate WIA devices on the system
		//
		hr = m_pWiaDevMgr->EnumDeviceInfo(WIA_DEVINFO_ENUM_LOCAL, &pWiaEnumDevInfo);
	}

	//
	// Reset the enumeration to start at the beginning of the list.
	//
	if (SUCCEEDED(hr)) {
		//
		// Call Reset on Enumerator
		//
		hr = pWiaEnumDevInfo->Reset();
	}

    BOOL bFound = FALSE;
	while ( SUCCEEDED(hr) ) {
		IWiaPropertyStorage *pIWiaPropStg	= NULL;
	    ULONG               ulFetched		= NULL;
		//
		// Get the next WIA device
		//
		hr = pWiaEnumDevInfo->Next(1, &pIWiaPropStg, &ulFetched);

		if (hr == S_OK)	{
			//
			// Get the device type of the device
			//
			PROPSPEC    PropSpec[3];
			PROPVARIANT PropVar[3];
			memset(PropVar,0,sizeof(PropVar));
			PropSpec[0].ulKind = PRSPEC_PROPID;
			PropSpec[0].propid = WIA_DIP_DEV_ID;
			PropSpec[1].ulKind = PRSPEC_PROPID;
			PropSpec[1].propid = WIA_DIP_DEV_TYPE;
			PropSpec[2].ulKind = PRSPEC_PROPID;
			PropSpec[2].propid = WIA_DIP_DEV_NAME;

			//
			// Get the type and the ID of each device
			//
			hr = pIWiaPropStg->ReadMultiple(sizeof(PropSpec)/sizeof(PROPSPEC),
											PropSpec, PropVar);

			//
			// If the device is a streaming video device/digital camera,
			//  get its ID
			//
			if (GET_STIDEVICE_TYPE(PropVar[1].lVal) == StiDeviceTypeStreamingVideo 
				|| GET_STIDEVICE_TYPE(PropVar[1].lVal) == StiDeviceTypeDigitalCamera) {
				std::wcerr	<< "WIA_DIP_DEV_ID :\t"		<< PropVar[0].bstrVal << std::endl
							<< "WIA_DIP_DEV_NAME :\t"	<< PropVar[2].bstrVal << std::endl;	
				bFound = TRUE;

				const size_t BUFFER_SIZE = 1024;
				char buf[BUFFER_SIZE];
				_bstr_t bstrIntermediate;

				bstrIntermediate.Assign(PropVar[0].bstrVal);
				sprintf_s((char*)buf, BUFFER_SIZE, "%s", (LPCTSTR)bstrIntermediate);
				char* strID = new char [strlen(buf)+1];
				strcpy_s( strID, strlen(buf)+1, buf );
				m_vCameraID.push_back(strID);

				bstrIntermediate.Assign(PropVar[2].bstrVal);
				sprintf_s((char*)buf, BUFFER_SIZE, "%s", (LPCTSTR)bstrIntermediate);
				char* strName = new char [strlen(buf)+1];
				strcpy_s( strID, strlen(buf)+1, buf );
				m_vCameraName.push_back(strName);
				delete [] strID;
				delete [] strName;

				//
				// Create a WIA device and get the recommended
				// images directory
				//
				IWiaItem *pRootItem = NULL;
				hr = m_pWiaDevMgr->CreateDevice(PropVar[0].bstrVal,
											&pRootItem);
				if (GET_STIDEVICE_TYPE(PropVar[1].lVal) == StiDeviceTypeStreamingVideo) {
					// ビデオカメラ特有の処理
					m_pCaptureFunc.push_back( &WIACamera::VideoCameraCapture );
				} else {
					// デジタルカメラ特有の処理
					m_pCaptureFunc.push_back( &WIACamera::DigitalCameraCapture );
				}
				if (SUCCEEDED(hr)) { 
					m_vRootItem.push_back(pRootItem);
				} else {
					m_vRootItem.push_back(NULL);
					throw "Error:\n";
					return hr;
				}
			}
		} else {
			break;
		}

		if (pIWiaPropStg) {
			pIWiaPropStg->Release();
			pIWiaPropStg = NULL;
		}
	}

	if (pWiaEnumDevInfo) {
		pWiaEnumDevInfo->Release();
		pWiaEnumDevInfo = NULL;
	}
	if (!bFound)
	{
		//
		// We did not find any WIA video streaming devices.  There is nothing left
		// to do.  Set result to E_FAIL
		//
		hr = E_FAIL;
		return hr;
	}


	m_iCount = (unsigned int)m_vRootItem.size();
	
    //
    // Return the result of creating the device manager
    //
    return hr;
}