Enable and Disable comport through c# code

  • Thread starter Thread starter Ravish Gowda
  • Start date Start date
R

Ravish Gowda

Guest
Hello

I am looking for code to enable and disable comport in PC. For which i used Win32 API and here goes the code below. But i am getting following exception error on calling that function..

"An unhandled exception of type 'System.ComponentModel.Win32Exception' occurred in Name.exe
Additional information: SetupAPI error: InWow64".

Kindly help me in resolving the issue.

CODE:

private static void EnableDevice(SafeDeviceInfoSetHandle handle, DeviceInfoData diData, bool enable)
{
PropertyChangeParameters @params = new PropertyChangeParameters();
// The size is just the size of the header, but we've flattened the structure.
// The header comprises the first two fields, both integer.
@params.Size = 8;
@params.DiFunction = DiFunction.PropertyChange;
@params.Scope = Scopes.Global;
if (enable)
{
@params.StateChange = StateChangeAction.Enable;
}
else
{
@params.StateChange = StateChangeAction.Disable;
}

bool result = NativeMethods.SetupDiSetClassInstallParams(handle, ref diData, ref @params, Marshal.SizeOf(@params));
if (result == false) throw new Win32Exception();
result = NativeMethods.SetupDiCallClassInstaller(DiFunction.PropertyChange, handle, ref diData);
if (result == false)
{
int err = Marshal.GetLastWin32Error();
if (err == (int)SetupApiError.NotDisableable)
throw new ArgumentException("Device can't be disabled (programmatically or in Device Manager).");
else if (err >= (int)SetupApiError.NoAssociatedClass && err <= (int)SetupApiError.OnlyValidateViaAuthenticode)
throw new Win32Exception("SetupAPI error: " + ((SetupApiError)err).ToString());
else
throw new Win32Exception();
}
}

Function public static void EnableMouse(bool enable)
{
// every type of device has a hard-coded GUID, this is the one for mice
Guid mouseGuid = new Guid("{4d36e978-e325-11ce-bfc1-08002be10318}");

// get this from the properties dialog box of this device in Device Manager
string instancePath = @"USB\VID_1FC9&PID_2002\DEMO00000000";

DeviceHelper.SetDeviceEnabled(mouseGuid, instancePath, enable);
}

Continue reading...
 
Back
Top