Автоматически отключать встроенную веб-камеру при подключении внешней?

6683
oKtosiTe

Я использую свой ноутбук в качестве настольного компьютера довольно часто, примерно в 75% случаев. В качестве настольной установки он имеет внешний монитор, динамики, клавиатуру, мышь и веб-камеру - последние три подключены через USB.
Затем он располагается таким образом, что его встроенная веб-камера становится бесполезной для распознавания лиц и видеочатов, однако некоторые из программ, которые я использую, не предлагают никакого способа выбора веб-камеры по умолчанию.

Поэтому мне было интересно, есть ли способ, с помощью утилиты, сценариев или иным образом, автоматически отключить встроенную веб-камеру при подключении внешней.

(Я использую Windows 7 на Asus Zenbook Prime UX32VD, если это поможет.)

0
Я думаю, что у меня есть рабочий сценарий, который должен справиться с этим. Можете ли вы подтвердить, что отключение встроенной веб-камеры заставит все программы обнаруживать внешнюю? and31415 10 лет назад 0
@ and31415, я попробую и свяжусь с вами как можно скорее. oKtosiTe 10 лет назад 0
Да, отключение устройства в диспетчере устройств дает желаемый эффект. @ and31415 oKtosiTe 10 лет назад 0
Вы проверяли программу просмотра событий на наличие событий? tumchaaditya 10 лет назад 0
@tumchaaditya: почему? Какие события? oKtosiTe 10 лет назад 0
Вы можете создать запланированное задание по этому идентификатору события и заставить его запускать пакетный файл, который включает / отключает необходимые устройства tumchaaditya 10 лет назад 1

3 ответа на вопрос

5
and31415

Theory first

  • We need to periodically check whether the external webcam is connected to the computer.
  • When the external webcam is plugged in, the built-in one should be disabled.
  • Then built-in device should be enabled back after the external camera is unplugged.

Preliminary steps

The proposed solution uses batch scripting and task scheduling techniques to handle all of this. Before we can actually jump to the juicy bits, we need to do a few things.

Obtain the Device Console (DevCon) utility

DevCon is a command-line tool that displays detailed information about devices, and lets you search for and manipulate devices from the command line. DevCon enables, disables, installs, configures, and removes devices on the local computer and displays detailed information about devices on local and remote computers.

  1. Download the appropriate .cab package depending on the operating system:

  2. Open the .cab archive and extract the file named fil[some letters and numbers]. It should be about 80 KB.

  3. Rename it to devcon.exe.

Note In order to enable/disable any device, devcon.exe must be run with admin rights.

Determine the required hardware identifiers

Windows identifies devices and the setup classes they belong to by using a special set of identifiers. These identifiers are used to match hardware devices with the device drivers that allow them to communicate with Windows.

One or more device IDs are assigned to a device by its manufacturer. One of them, the hardware ID, is very specific - down to the make, model, and even the firmware version of the device. Other device IDs are also assigned, and are more generic, with the IDs possibly being assigned to other devices from the manufacturer that are compatible at some level.

Source: Discovering Hardware IDs and Device Setup Classes for your Devices

  1. Plug the external webcam in.
  2. Open the Device Manager (devmgmt.msc).
  3. Find your built-in camera in the list.
  4. Right-click the entry for the device, and then click Properties.
  5. Select the Details tab and choose Hardware Ids from the property list.
  6. Right-click the first value shown and copy it. Take note of the value somewhere.
  7. Repeat steps 3-6 for the external webcam.

Creating the batch script

  1. Save the following code as WebcamCheck.cmd:

    @echo off REM ensure there at least 2 parameters if "%~2" == "" exit /b 2 REM verify devcon.exe is not missing cd /d "%~dp0" if not exist devcon.exe exit /b 3 REM set the interval to 15 seconds if not specified if "%~3" == "" (set interval=15) else (set interval=%3) :poll for /f "tokens=1 delims=\" %%G in ("%~2") do (devcon.exe find *%%G* | findstr /i /c:"%~2" >nul) goto :check%errorlevel% :check0 devcon.exe status "%~1" | findstr /i /c:"disabled" >nul if %errorlevel% == 1 (devcon.exe disable "%~1") :wait timeout /t %interval% /nobreak >nul goto :poll :check1 devcon.exe status "%~1" | findstr /i /c:"disabled" >nul if %errorlevel% == 0 (devcon.exe enable "%~1") goto :wait 
  2. Copy the devcon.exe file and paste into the same directory as the file you just saved.

How it works

The script takes three parameters: the first one is the target device ID (the built-in webcam); the second one is the trigger device ID (the external webcam); the third one is the polling interval (in seconds), and it's optional.

At first the script will make sure there are enough parameters, and that devcon.exe isn't missing.

When no polling interval is specified, the default value will be used instead (15 seconds). The value is used to determine how many seconds should elapse between each device check. Lowering the value means the detection is faster, which in turns means there's more system overhead. Before trying a different value, test it with the default one and see how it goes. Either way, I wouldn't recommend going below 10 seconds.

The batch script requires generic device IDs, which use the following format:

XXX\VID_YYYY&PID_ZZZZ 

XXX is the device class (e.g. USB, PCI, etc.); YYYY is the Vendor ID, an unique value assigned to hardware manufacturers; ZZZZ is the Product ID, which identifies the device model.

For example, if you got a device ID like this:

USB\VID_1D4D&PID_1002&REV_0039&MI_00 

the generic ID would be:

USB\VID_1D4D&PID_1002 

After checking whether the trigger device (external webcam) is connected, the script will either disable or enable the target device (built-in webcam), unless it's disabled/enabled already.

Scheduling it

The only thing we need now is to make the batch script start automatically at log on.

  1. Open the Task Scheduler (taskschd.msc) and click Action > Create Task.
  2. Name it WebcamCheck.
  3. While in the General tab, click Change User or Group.
  4. Type system in the textbox, click Check Names, and then click OK.
  5. Enable the Run with highest privileges option.
  6. Change the Configure for value to Windows 7, Windows Server 2008 R2.
  7. Select the Triggers tab, and click New.
  8. Change the Begin the task to At log on, then press OK.
  9. Switch to the Actions tab, and click New.
  10. Type "X:\Path\to\WebcamCheck.cmd" in the Program/script textbox, replacing it with the actual file path.
  11. Type "XXX\VID_YYYY&PID_ZZZZ" "AAA\VID_BBBB&PID_CCCC" in the Add arguments textbox, replacing the device IDs with the proper values.
  12. Click the Conditions tab and uncheck Start the task only if the computer is on AC power option.
  13. Select the Settings tab, and uncheck both the Allow task to be run on demand and Stop the task if it runs longer than fields.
  14. Enable the Run task as soon as possible after a scheduled start is missed option.
  15. Leave all other settings to default values and press OK.

Note If you want the built-in webcam to be disabled as soon as possible, connect the external one before logging in.


Update

Here's a simplified version of the batch script which will check the external camera only when started and then exit:

@echo off REM ensure there at least 2 parameters if "%~2" == "" exit /b 2 REM verify devcon.exe is not missing cd /d "%~dp0" if not exist devcon.exe exit /b 3 :check for /f "tokens=1 delims=\" %%G in ("%~2") do (devcon.exe find *%%G* | findstr /i /c:"%~2" >nul) goto :check%errorlevel% :check0 devcon.exe status "%~1" | findstr /i /c:"disabled" >nul if %errorlevel% == 1 (devcon.exe disable "%~1") exit /b :check1 devcon.exe status "%~1" | findstr /i /c:"disabled" >nul if %errorlevel% == 0 (devcon.exe enable "%~1") exit /b 
Надеюсь, у меня еще будет достаточно времени, чтобы проверить это до истечения срока действия награды. Если нет, я могу наградить новый позже. Хотя мне не нужно, чтобы компьютер постоянно отслеживал внешнюю камеру, я верю, что смогу извлечь из вашего ответа ряд полезных моментов. oKtosiTe 10 лет назад 0
Вы имеете в виду, что проверка внешней камеры возможна только при входе в систему? and31415 10 лет назад 0
Да, конечно. oKtosiTe 10 лет назад 0
В любом случае, у меня пока не будет времени проверить ответ, но, похоже, вы думали в одном направлении (devcon и скрипт) и приложили немало усилий, награда заслуженная IMO. Почти наверняка примут позже. Спасибо. oKtosiTe 10 лет назад 0
0
XcisioN

Вы можете попробовать отключить веб-камеру через панель управления или в диспетчере устройств. Это должно позволить установить внешнюю веб-камеру и быть единственной веб-камерой, которая работает в данный момент. после этого вы всегда можете просто включить устройство снова.

Надеюсь это поможет.

Я надеялся сделать это как-нибудь автоматически. Мне все еще непонятно, что в Windows нет настроек для этого ... oKtosiTe 10 лет назад 1
@oKtosiTe: в Windows не может быть всего, что вы можете себе представить! tumchaaditya 10 лет назад 0
@tumchaaditya, и все же он может автоматически отключать звук от внешних динамиков, когда подключены наушники, и выключать экран ноутбука, когда подключен внешний монитор. Synetech 10 лет назад 1
Внешние динамики обычно обрабатываются аудио драйверами, а не окнами. Ищите SU, и вы обнаружите множество вопросов о том, что эта функция не работает из-за проблемы с драйвером. И окна могут или не могут отключить дисплей ноутбука в зависимости от того, как вы настроили его, когда вы в последний раз подключали внешний дисплей. Он просто запоминает эту настройку. tumchaaditya 10 лет назад 0
@tumchaaditya: Встроенная функция Windows не имеет значения. Я приму любой ответ, который каким-то образом удастся автоматизировать, будь то с помощью пакетного скрипта, утилиты, драйвера-обертки или акулы с чертовым лазером, прикрепленным к его голове. oKtosiTe 10 лет назад 1
0
tarkan dost

You can try a Portable freeware Aplication "WebCam On-Off v1.0" it has Cmd suppor too http://www.sordum.org/8585/webcam-on-off-dont-let-your-webcam-spy-on-you/

Добро пожаловать в Супер пользователя! Пожалуйста, прочитайте [Как я рекомендую программное обеспечение] (http://meta.superuser.com/questions/5329/how-do-i-recommend-software-in-my-answers/5330#5330) для получения некоторых советов о том, как Вы должны рекомендовать программное обеспечение. По крайней мере, вы должны предоставить дополнительную информацию о программном обеспечении. Mokubai 9 лет назад 0

Похожие вопросы