本文整理汇总了C#中Microsoft.Win32.SafeHandles.SafeFileHandle.Close方法的典型用法代码示例。如果您正苦于以下问题:C# SafeFileHandle.Close方法的具体用法?C# SafeFileHandle.Close怎么用?C# SafeFileHandle.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.Win32.SafeHandles.SafeFileHandle
的用法示例。
在下文中一共展示了SafeFileHandle.Close方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: FindTheHid
//.........这里部分代码省略.........
if (success)
{
Tracer.Trace(" HIDD_ATTRIBUTES structure filled without error.");
Tracer.Trace(" Structure size: " + MyHid.DeviceAttributes.Size);
Tracer.Trace(" Vendor ID: " + Convert.ToString(MyHid.DeviceAttributes.VendorID, 16));
Tracer.Trace(" Product ID: " + Convert.ToString(MyHid.DeviceAttributes.ProductID, 16));
Tracer.Trace(" Version Number: " + Convert.ToString(MyHid.DeviceAttributes.VersionNumber, 16));
// Find out if the device matches the one we're looking for.
if ((MyHid.DeviceAttributes.VendorID == myVendorID) && (MyHid.DeviceAttributes.ProductID == myProductID))
{
Tracer.Trace(" My device detected");
// Display the information in form's list box.
Tracer.Trace("Device detected:");
Tracer.Trace(" Vendor ID= " + Convert.ToString(MyHid.DeviceAttributes.VendorID, 16));
Tracer.Trace(" Product ID = " + Convert.ToString(MyHid.DeviceAttributes.ProductID, 16));
myDeviceDetected = true;
// Save the DevicePathName for OnDeviceChange().
myDevicePathName = devicePathName[memberIndex];
}
else
{
// It's not a match, so close the handle.
myDeviceDetected = false;
hidHandle.Close();
}
}
else
{
// There was a problem in retrieving the information.
Tracer.Trace(" Error in filling HIDD_ATTRIBUTES structure.");
myDeviceDetected = false;
hidHandle.Close();
}
}
// Keep looking until we find the device or there are no devices left to examine.
memberIndex = memberIndex + 1;
}
while (!((myDeviceDetected || (memberIndex == devicePathName.Length))));
}
if (myDeviceDetected)
{
// The device was detected.
// Register to receive notifications if the device is removed or attached.
success = MyDeviceManagement.RegisterForDeviceNotifications(myDevicePathName, m_mainForm.Handle, hidGuid, ref deviceNotificationHandle);
Tracer.Trace("RegisterForDeviceNotifications = " + success);
// Learn the capabilities of the device.
MyHid.Capabilities = MyHid.GetDeviceCapabilities(hidHandle);
示例2: SafeCloseHandle
internal static void SafeCloseHandle(SafeFileHandle handle)
{
if (handle != null && !handle.IsInvalid)
handle.Close();
}
示例3: CancelTransfer
/// <summary>
/// closes open handles to a device.
/// </summary>
///
/// <param name="hidHandle"> the handle for learning about the device and exchanging Feature reports. </param>
/// <param name="readHandle"> the handle for reading Input reports from the device. </param>
/// <param name="writeHandle"> the handle for writing Output reports to the device. </param>
internal void CancelTransfer(SafeFileHandle hidHandle, SafeFileHandle readHandle, SafeFileHandle writeHandle, IntPtr eventObject)
{
try
{
// ***
// API function: CancelIo
// Purpose: Cancels a call to ReadFile
// Accepts: the device handle.
// Returns: True on success, False on failure.
// ***
FileIO.CancelIo(readHandle);
Debug.WriteLine( "************ReadFile error*************" );
String functionName = "CancelIo";
Debug.WriteLine(MyDebugging.ResultOfAPICall(functionName));
Debug.WriteLine( "" );
// The failure may have been because the device was removed,
// so close any open handles and
// set myDeviceDetected=False to cause the application to
// look for the device on the next attempt.
if ( ( !( hidHandle.IsInvalid ) ) )
{
hidHandle.Close();
}
if ( ( !( readHandle.IsInvalid ) ) )
{
readHandle.Close();
}
if ( ( !( writeHandle.IsInvalid ) ) )
{
writeHandle.Close();
}
}
catch ( Exception ex )
{
DisplayException( MODULE_NAME, ex );
throw ;
}
}
示例4: Write
/// <summary>
/// writes an Output report to the device.
/// </summary>
///
/// <param name="outputReportBuffer"> contains the report ID and report data. </param>
/// <param name="writeHandle"> handle to the device. </param>
///
/// <returns>
/// True on success. False on failure.
/// </returns>
internal override Boolean Write( Byte[] outputReportBuffer, SafeFileHandle writeHandle )
{
Int32 numberOfBytesWritten = 0;
Boolean success = false;
try
{
// The host will use an interrupt transfer if the the HID has an interrupt OUT
// endpoint (requires USB 1.1 or later) AND the OS is NOT Windows 98 Gold (original version).
// Otherwise the the host will use a control transfer.
// The application doesn't have to know or care which type of transfer is used.
numberOfBytesWritten = 0;
// ***
// API function: WriteFile
// Purpose: writes an Output report to the device.
// Accepts:
// A handle returned by CreateFile
// An integer to hold the number of bytes written.
// Returns: True on success, False on failure.
// ***
success = FileIO.WriteFile(writeHandle, outputReportBuffer, outputReportBuffer.Length, ref numberOfBytesWritten, IntPtr.Zero);
Debug.Print( "WriteFile success = " + success );
if ( !( ( success ) ) )
{
if ( ( !( writeHandle.IsInvalid ) ) )
{
writeHandle.Close();
}
}
return success;
}
catch ( Exception ex )
{
DisplayException( MODULE_NAME, ex );
throw ;
}
}
示例5: CleanupHandle
private void CleanupHandle(SafeFileHandle handle)
{
if (handle != null && !handle.IsClosed)
{
InteropKernel32.CloseHandle(handle);
handle.Close();
}
}
示例6: CancelTransfer
/// <summary>
/// closes open handles to a device.
/// </summary>
///
/// <param name="hidHandle"> the handle for learning about the device and exchanging Feature reports. </param>
/// <param name="readHandle"> the handle for reading Input reports from the device. </param>
/// <param name="writeHandle"> the handle for writing Output reports to the device. </param>
private void CancelTransfer(SafeFileHandle hidHandle, SafeFileHandle readHandle, SafeFileHandle writeHandle)
{
// ***
// API function: CancelIo
// Purpose: Cancels a call to ReadFile
// Accepts: the device handle.
// Returns: True on success, False on failure.
// ***
NativeMethods.CancelIo(readHandle);
// The failure may have been because the device was removed,
// so close any open handles and
// set myDeviceDetected=False to cause the application to
// look for the device on the next attempt.
if ( ( !( hidHandle.IsInvalid ) ) )
{
hidHandle.Close();
}
if ( ( !( readHandle.IsInvalid ) ) )
{
readHandle.Close();
}
if ( ( !( writeHandle.IsInvalid ) ) )
{
writeHandle.Close();
}
}
示例7: WndProc
//-------------------------------------------------------END CUT AND PASTE BLOCK-------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------BEGIN CUT AND PASTE BLOCK-----------------------------------------------------------------------------------
//This is a callback function that gets called when a Windows message is received by the form.
//We will receive various different types of messages, but the ones we really want to use are the WM_DEVICECHANGE messages.
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_DEVICECHANGE)
{
if (((int)m.WParam == DBT_DEVICEARRIVAL) || ((int)m.WParam == DBT_DEVICEREMOVEPENDING) || ((int)m.WParam == DBT_DEVICEREMOVECOMPLETE) || ((int)m.WParam == DBT_CONFIGCHANGED))
{
//WM_DEVICECHANGE messages by themselves are quite generic, and can be caused by a number of different
//sources, not just your USB hardware device. Therefore, must check to find out if any changes relavant
//to your device (with known VID/PID) took place before doing any kind of opening or closing of handles/endpoints.
//(the message could have been totally unrelated to your application/USB device)
if (CheckIfPresentAndGetUSBDevicePath()) //Check and make sure at least one device with matching VID/PID is attached
{
//If executes to here, this means the device is currently attached and was found.
//This code needs to decide however what to do, based on whether or not the device was previously known to be
//attached or not.
if ((AttachedState == false) || (AttachedButBroken == true)) //Check the previous attachment state
{
uint ErrorStatusWrite;
uint ErrorStatusRead;
//We obtained the proper device path (from CheckIfPresentAndGetUSBDevicePath() function call), and it
//is now possible to open read and write handles to the device.
WriteHandleToUSBDevice = CreateFile(DevicePath, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
ErrorStatusWrite = (uint)Marshal.GetLastWin32Error();
ReadHandleToUSBDevice = CreateFile(DevicePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
ErrorStatusRead = (uint)Marshal.GetLastWin32Error();
if ((ErrorStatusWrite == ERROR_SUCCESS) && (ErrorStatusRead == ERROR_SUCCESS))
{
AttachedState = true; //Let the rest of the PC application know the USB device is connected, and it is safe to read/write to it
AttachedButBroken = false;
StatusBox_txtbx.Text = "Device Found, AttachedState = TRUE";
}
else //for some reason the device was physically plugged in, but one or both of the read/write handles didn't open successfully...
{
AttachedState = false; //Let the rest of this application known not to read/write to the device.
AttachedButBroken = true; //Flag so that next time a WM_DEVICECHANGE message occurs, can retry to re-open read/write pipes
if (ErrorStatusWrite == ERROR_SUCCESS)
WriteHandleToUSBDevice.Close();
if (ErrorStatusRead == ERROR_SUCCESS)
ReadHandleToUSBDevice.Close();
}
}
//else we did find the device, but AttachedState was already true. In this case, don't do anything to the read/write handles,
//since the WM_DEVICECHANGE message presumably wasn't caused by our USB device.
}
else //Device must not be connected (or not programmed with correct firmware)
{
if (AttachedState == true) //If it is currently set to true, that means the device was just now disconnected
{
AttachedState = false;
WriteHandleToUSBDevice.Close();
ReadHandleToUSBDevice.Close();
}
AttachedState = false;
AttachedButBroken = false;
}
}
} //end of: if(m.Msg == WM_DEVICECHANGE)
base.WndProc(ref m);
}
示例8: Form1
//--------------- End of Global Varibles ------------------
//-------------------------------------------------------END CUT AND PASTE BLOCK-------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------
//Need to check "Allow unsafe code" checkbox in build properties to use unsafe keyword. Unsafe is needed to
//properly interact with the unmanged C++ style APIs used to find and connect with the USB device.
public unsafe Form1()
{
InitializeComponent();
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------BEGIN CUT AND PASTE BLOCK-----------------------------------------------------------------------------------
//Additional constructor code
//Initialize tool tips, to provide pop up help when the mouse cursor is moved over objects on the form.
ANxVoltageToolTip.SetToolTip(this.ANxVoltage_lbl, "If using a board/PIM without a potentiometer, apply an adjustable voltage to the I/O pin.");
ANxVoltageToolTip.SetToolTip(this.progressBar1, "If using a board/PIM without a potentiometer, apply an adjustable voltage to the I/O pin.");
ToggleLEDToolTip.SetToolTip(this.ToggleLEDs_btn, "Sends a packet of data to the USB device.");
PushbuttonStateTooltip.SetToolTip(this.PushbuttonState_lbl, "Try pressing pushbuttons on the USB demo board/PIM.");
//Register for WM_DEVICECHANGE notifications. This code uses these messages to detect plug and play connection/disconnection events for USB devices
DEV_BROADCAST_DEVICEINTERFACE DeviceBroadcastHeader = new DEV_BROADCAST_DEVICEINTERFACE();
DeviceBroadcastHeader.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
DeviceBroadcastHeader.dbcc_size = (uint)Marshal.SizeOf(DeviceBroadcastHeader);
DeviceBroadcastHeader.dbcc_reserved = 0; //Reserved says not to use...
DeviceBroadcastHeader.dbcc_classguid = InterfaceClassGuid;
//Need to get the address of the DeviceBroadcastHeader to call RegisterDeviceNotification(), but
//can't use "&DeviceBroadcastHeader". Instead, using a roundabout means to get the address by
//making a duplicate copy using Marshal.StructureToPtr().
IntPtr pDeviceBroadcastHeader = IntPtr.Zero; //Make a pointer.
pDeviceBroadcastHeader = Marshal.AllocHGlobal(Marshal.SizeOf(DeviceBroadcastHeader)); //allocate memory for a new DEV_BROADCAST_DEVICEINTERFACE structure, and return the address
Marshal.StructureToPtr(DeviceBroadcastHeader, pDeviceBroadcastHeader, false); //Copies the DeviceBroadcastHeader structure into the memory already allocated at DeviceBroadcastHeaderWithPointer
RegisterDeviceNotification(this.Handle, pDeviceBroadcastHeader, DEVICE_NOTIFY_WINDOW_HANDLE);
//Now make an initial attempt to find the USB device, if it was already connected to the PC and enumerated prior to launching the application.
//If it is connected and present, we should open read and write handles to the device so we can communicate with it later.
//If it was not connected, we will have to wait until the user plugs the device in, and the WM_DEVICECHANGE callback function can process
//the message and again search for the device.
if(CheckIfPresentAndGetUSBDevicePath()) //Check and make sure at least one device with matching VID/PID is attached
{
uint ErrorStatusWrite;
uint ErrorStatusRead;
//We now have the proper device path, and we can finally open read and write handles to the device.
WriteHandleToUSBDevice = CreateFile(DevicePath, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
ErrorStatusWrite = (uint)Marshal.GetLastWin32Error();
ReadHandleToUSBDevice = CreateFile(DevicePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
ErrorStatusRead = (uint)Marshal.GetLastWin32Error();
if((ErrorStatusWrite == ERROR_SUCCESS) && (ErrorStatusRead == ERROR_SUCCESS))
{
AttachedState = true; //Let the rest of the PC application know the USB device is connected, and it is safe to read/write to it
AttachedButBroken = false;
StatusBox_txtbx.Text = "Device Found, AttachedState = TRUE";
}
else //for some reason the device was physically plugged in, but one or both of the read/write handles didn't open successfully...
{
AttachedState = false; //Let the rest of this application known not to read/write to the device.
AttachedButBroken = true; //Flag so that next time a WM_DEVICECHANGE message occurs, can retry to re-open read/write pipes
if(ErrorStatusWrite == ERROR_SUCCESS)
WriteHandleToUSBDevice.Close();
if(ErrorStatusRead == ERROR_SUCCESS)
ReadHandleToUSBDevice.Close();
}
}
else //Device must not be connected (or not programmed with correct firmware)
{
AttachedState = false;
AttachedButBroken = false;
}
if (AttachedState == true)
{
StatusBox_txtbx.Text = "Device Found, AttachedState = TRUE";
}
else
{
StatusBox_txtbx.Text = "Device not found, verify connect/correct firmware";
}
ReadWriteThread.RunWorkerAsync(); //Recommend performing USB read/write operations in a separate thread. Otherwise,
//the Read/Write operations are effectively blocking functions and can lock up the
//user interface if the I/O operations take a long time to complete.
//-------------------------------------------------------END CUT AND PASTE BLOCK-------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------
}
示例9: FindTheHids
public String[] FindTheHids()
{
Boolean deviceFound = false;
String[] devicePathName = new String[128];
String functionName = "";
Guid hidGuid = Guid.Empty;
Int32 memberIndex = 0;
Int16 myProductID = 0;
Int16 myVendorID = 0;
//Int32 product = 0;
//Int32 vendor = 0;
Boolean success = false;
try
{
myDeviceDetected = false;
//TODO: WTF is going on with this formatting?
//vendor = 0xAFEF;
//product = 0x0F01;
myVendorID = -20497;
myProductID = 3841;
// ***
// API function: 'HidD_GetHidGuid
// Purpose: Retrieves the interface class GUID for the HID class.
// Accepts: 'A System.Guid object for storing the GUID.
// ***
Hid.HidD_GetHidGuid(ref hidGuid);
functionName = "GetHidGuid";
Debug.WriteLine(MyDebugging.ResultOfAPICall(functionName));
//Console.Out.WriteLine(MyDebugging.ResultOfAPICall(functionName));
Debug.WriteLine(" GUID for system HIDs: " + hidGuid.ToString());
//Console.Out.WriteLine(" GUID for system HIDs: " + hidGuid.ToString());
// Fill an array with the device path names of all attached HIDs.
deviceFound = MyDeviceManagement.FindDeviceFromGuid(hidGuid, ref devicePathName);
for (int p = 0; p < devicePathName.Length; p++)
{
Console.Out.WriteLine(devicePathName[p]);
}
if (deviceFound)
{
for (int m = 0; m < devicePathName.Length; m++)
{
hidHandle = FileIO.CreateFile(devicePathName[memberIndex], 0, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0);
functionName = "CreateFile";
Debug.WriteLine(MyDebugging.ResultOfAPICall(functionName));
if (!hidHandle.IsInvalid)
{
MyHid.DeviceAttributes.Size = Marshal.SizeOf(MyHid.DeviceAttributes);
success = Hid.HidD_GetAttributes(hidHandle, ref MyHid.DeviceAttributes);
if (success)
{
if ((MyHid.DeviceAttributes.VendorID == myVendorID) & (MyHid.DeviceAttributes.ProductID == myProductID))
{
Debug.WriteLine(" My device detected");
//Console.Out.WriteLine(" My device detected");
myDeviceDetected = true;
// Save the DevicePathName for OnDeviceChange().
myDevicePathName = devicePathName[memberIndex];
}
else
{
// It's not a match, so close the handle.
myDeviceDetected = false;
hidHandle.Close();
}
}
else
{
// There was a problem in retrieving the information.
Debug.WriteLine(" Error in filling HIDD_ATTRIBUTES structure.");
//Console.Out.WriteLine(" Error in filling HIDD_ATTRIBUTES structure.");
myDeviceDetected = false;
hidHandle.Close();
}
}
}
if (myDeviceDetected)
{
MyHid.Capabilities = MyHid.GetDeviceCapabilities(hidHandle);
if (success)
{
// Find out if the device is a system mouse or keyboard.
hidUsage = MyHid.GetHidUsage(MyHid.Capabilities);
// Get the Input report buffer size.
//GetInputReportBufferSize();
//cmdInputReportBufferSize.Enabled = true;
// Get handles to use in requesting Input and Output reports.
readHandle = FileIO.CreateFile(myDevicePathName, FileIO.GENERIC_READ, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, FileIO.FILE_FLAG_OVERLAPPED, 0);
//.........这里部分代码省略.........
示例10: GetGuids
public String[] GetGuids()
{
Boolean deviceFound = false;
String[] devicePathName = new String[128];
Queue<string> queueDevicePathName = new Queue<string>();
String functionName = "";
String devpath;
Guid hidGuid = Guid.Empty;
Int32 memberIndex = 0;
Int16 myVendorID = -20497;
Int16 myProductID = 3841;
Boolean success = false;
Hid.HidD_GetHidGuid(ref hidGuid);
deviceFound = MyDeviceManagement.FindDeviceFromGuid(hidGuid, ref devicePathName);
for (int p = 0; p < devicePathName.Length; p++)
{
Console.Out.WriteLine(devicePathName[p]);
}
if (deviceFound)
{
for (int m = 0; m < devicePathName.Length; m++)
{
hidHandle = FileIO.CreateFile(devicePathName[m], 0, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0);
functionName = "CreateFile";
Debug.WriteLine(MyDebugging.ResultOfAPICall(functionName));
if (!hidHandle.IsInvalid)
{
MyHid.DeviceAttributes.Size = Marshal.SizeOf(MyHid.DeviceAttributes);
success = Hid.HidD_GetAttributes(hidHandle, ref MyHid.DeviceAttributes);
if (success)
{
if ((MyHid.DeviceAttributes.VendorID == myVendorID) & (MyHid.DeviceAttributes.ProductID == myProductID))
{
Debug.WriteLine(" My device detected");
//Console.Out.WriteLine(" My device detected");
myDeviceDetected = true;
// Save the DevicePathName for OnDeviceChange().
//myDevicePathName = devicePathName[memberIndex];
devpath = devicePathName[m];
hidHandle.Close();
queueDevicePathName.Enqueue(devpath);
}
else
{
// It's not a match, so close the handle.
myDeviceDetected = false;
hidHandle.Close();
}
}
else
{
// There was a problem in retrieving the information.
Debug.WriteLine(" Error in filling HIDD_ATTRIBUTES structure.");
//Console.Out.WriteLine(" Error in filling HIDD_ATTRIBUTES structure.");
myDeviceDetected = false;
hidHandle.Close();
}
}
}
}
return queueDevicePathName.ToArray();
}
示例11: _CloseHandle
private static void _CloseHandle(SafeFileHandle h)
{
try
{
if (h != null)
{
h.Close();
h.Dispose();
}
}
catch
{
//Eat...
}
}