Click here to Skip to main content
15,887,434 members
Home / Discussions / C#
   

C#

 
GeneralRe: cant send file bigger that 1 megabit ( Server_client ) Pin
Peter_in_27806-Jun-18 20:33
professionalPeter_in_27806-Jun-18 20:33 
Questionhow to calculate in c# Pin
denis.larocque5-Jun-18 17:31
denis.larocque5-Jun-18 17:31 
AnswerRe: how to calculate in c# Pin
OriginalGriff5-Jun-18 19:21
mveOriginalGriff5-Jun-18 19:21 
GeneralRe: how to calculate in c# Pin
Richard Andrew x648-Jun-18 12:02
professionalRichard Andrew x648-Jun-18 12:02 
GeneralRe: how to calculate in c# Pin
OriginalGriff8-Jun-18 19:28
mveOriginalGriff8-Jun-18 19:28 
GeneralRe: how to calculate in c# Pin
Richard Andrew x649-Jun-18 2:31
professionalRichard Andrew x649-Jun-18 2:31 
GeneralRe: how to calculate in c# Pin
OriginalGriff9-Jun-18 2:40
mveOriginalGriff9-Jun-18 2:40 
QuestionConvert C++ code, with calls to ATL, into C# to quickly get com ports and their friendly names? Pin
arnold_w5-Jun-18 5:13
arnold_w5-Jun-18 5:13 
I am writing a C# application with Visual Studio Express 2005 and I need to query the available com ports and their friendly names. The first part is easy, I can simply call SerialPort.GetPortNames(). In order to get the friendly names, I found the following code on the internet:

for (int i = 0; i < availableComPorts.Length; i++)
{
    try
    {
        string temp = "(" + availableComPorts[i] + ")";
        foreach (ManagementObject queryObj in searcher.Get())
        {
            if ((queryObj["Name"] != null) && (queryObj["Name"].ToString().EndsWith(temp)))
            {
                ComPortInfo comPortsInfo = new ComPortInfo();
                comPortsInfo.officalName             = availableComPorts[i];
                comPortsInfo.userfriendlyDescription = queryObj["Caption"].ToString().Replace("(" + availableComPorts[i] + ")", "").Trim();
                comPortsInfo.manufacturer            = queryObj["Manufacturer"].ToString();
                comPortInfoArrayList.Add(comPortsInfo);
            }
        }
    }
    catch (Exception)
    {
    }
}


The problem with the code above is that it takes about 1.5 seconds(!) to execute on my computer which is too slow. After further investigations I found the following post [winapi - How do I get a list of available serial ports in Win32? - Stack Overflow](https://stackoverflow.com/questions/1388871/how-do-i-get-a-list-of-available-serial-ports-in-win32) which refers to the following project: [CEnumerateSerial v1.34](http://www.naughter.com/enumser.html). This project seems very promising, especially the "Device Manager (SetupAPI - GUID_DEVINTERFACE_COMPORT)" method, which executes extremely quickly on my computer:

_Return_type_success_(return != 0) BOOL CEnumerateSerial::QueryRegistryPortName(_In_ ATL::CRegKey& deviceKey, _Out_ int& nPort)
{
  //What will be the return value from the method (assume the worst)
  BOOL bAdded = FALSE;

  //Read in the name of the port
  LPTSTR pszPortName = nullptr;
  if (RegQueryValueString(deviceKey, _T("PortName"), pszPortName))
  {
    //If it looks like "COMX" then
    //add it to the array which will be returned
    const size_t nLen = _tcslen(pszPortName);
    if (nLen > 3)
    {
      if ((_tcsnicmp(pszPortName, _T("COM"), 3) == 0) && IsNumeric((pszPortName + 3), FALSE))
      {
        //Work out the port number
        nPort = _ttoi(pszPortName + 3);

        bAdded = TRUE;
      }
    }
    LocalFree(pszPortName);
  }

  return bAdded;
}


_Return_type_success_(return != 0) BOOL CEnumerateSerial::QueryUsingSetupAPI(const GUID& guid, _In_ DWORD dwFlags, _Inout_ CPortsArray& ports, _Inout_ CNamesArray& friendlyNames)
{
  //Set our output parameters to sane defaults
#ifndef CENUMERATESERIAL_MFC_EXTENSIONS
  ports.clear();
  friendlyNames.clear();
#else
  ports.RemoveAll();
  friendlyNames.RemoveAll();
#endif //#ifndef CENUMERATESERIAL_MFC_EXTENSIONS

  //Create a "device information set" for the specified GUID
  HDEVINFO hDevInfoSet = SetupDiGetClassDevs(&guid, nullptr, nullptr, dwFlags);
  if (hDevInfoSet == INVALID_HANDLE_VALUE)
    return FALSE;

  //Finally do the enumeration
  BOOL bMoreItems = TRUE;
  int nIndex = 0;
  SP_DEVINFO_DATA devInfo = { 0 };
  while (bMoreItems)
  {
    //Enumerate the current device
    devInfo.cbSize = sizeof(SP_DEVINFO_DATA);
    bMoreItems = SetupDiEnumDeviceInfo(hDevInfoSet, nIndex, &devInfo);
    if (bMoreItems)
    {
      //Did we find a serial port for this device
      BOOL bAdded = FALSE;

      //Get the registry key which stores the ports settings
      ATL::CRegKey deviceKey;
      deviceKey.Attach(SetupDiOpenDevRegKey(hDevInfoSet, &devInfo, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_QUERY_VALUE));
      if (deviceKey != INVALID_HANDLE_VALUE)
      {
        int nPort = 0;
        if (QueryRegistryPortName(deviceKey, nPort))
        {
        #ifndef CENUMERATESERIAL_MFC_EXTENSIONS
          ports.push_back(nPort);
        #else
          ports.Add(nPort);
        #endif //#ifndef CENUMERATESERIAL_MFC_EXTENSIONS
          bAdded = TRUE;
        }
      }

      //If the port was a serial port, then also try to get its friendly name
      if (bAdded)
      {
        ATL::CHeapPtr<BYTE> byFriendlyName;
        if (QueryDeviceDescription(hDevInfoSet, devInfo, byFriendlyName))
        {
        #ifndef CENUMERATESERIAL_MFC_EXTENSIONS
          friendlyNames.push_back(reinterpret_cast<LPCTSTR>(byFriendlyName.m_pData));
        #else
          friendlyNames.Add(reinterpret_cast<LPCTSTR>(byFriendlyName.m_pData));
        #endif //#ifndef CENUMERATESERIAL_MFC_EXTENSIONS
        }
        else
        {
        #ifndef CENUMERATESERIAL_MFC_EXTENSIONS
          friendlyNames.push_back(_T(""));
        #else
          friendlyNames.Add(_T(""));
        #endif //#ifndef CENUMERATESERIAL_MFC_EXTENSIONS
        }
      }
    }

    ++nIndex;
  }


Now, the problem is that I don't know how to convert this to C#. I was able to convert some of it into C# using P/Invoke, for example:
[DllImport("setupapi.dll", CharSet = CharSet.Auto)]
static extern IntPtr SetupDiGetClassDevs(
   ref Guid ClassGuid,
   [MarshalAs(UnmanagedType.LPTStr)] string Enumerator,
   IntPtr hwndParent,
   uint Flags);

[StructLayout(LayoutKind.Sequential)]
struct SP_DEVINFO_DATA
{
    public UInt32 cbSize;
    public Guid ClassGuid;
    public UInt32 DevInst;
    public IntPtr Reserved;
}

[DllImport("setupapi.dll", SetLastError = true)]
static extern bool SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet,
                                         uint MemberIndex,
                                         ref SP_DEVINFO_DATA DeviceInfoData);


but I'm unable to figure out how to convert the calls to ATL. Can anybody please advice on how I can convert the code to C#?
AnswerRe: Convert C++ code, with calls to ATL, into C# to quickly get com ports and their friendly names? Pin
Gerry Schmitz5-Jun-18 5:26
mveGerry Schmitz5-Jun-18 5:26 
GeneralRe: Convert C++ code, with calls to ATL, into C# to quickly get com ports and their friendly names? Pin
arnold_w5-Jun-18 7:15
arnold_w5-Jun-18 7:15 
GeneralRe: Convert C++ code, with calls to ATL, into C# to quickly get com ports and their friendly names? Pin
Gerry Schmitz5-Jun-18 7:51
mveGerry Schmitz5-Jun-18 7:51 
GeneralRe: Convert C++ code, with calls to ATL, into C# to quickly get com ports and their friendly names? Pin
arnold_w5-Jun-18 10:16
arnold_w5-Jun-18 10:16 
GeneralRe: Convert C++ code, with calls to ATL, into C# to quickly get com ports and their friendly names? Pin
Gerry Schmitz6-Jun-18 5:31
mveGerry Schmitz6-Jun-18 5:31 
AnswerRe: Convert C++ code, with calls to ATL, into C# to quickly get com ports and their friendly names? Pin
Jochen Arndt5-Jun-18 21:24
professionalJochen Arndt5-Jun-18 21:24 
GeneralRe: Convert C++ code, with calls to ATL, into C# to quickly get com ports and their friendly names? Pin
arnold_w6-Jun-18 0:39
arnold_w6-Jun-18 0:39 
QuestionIN DESPERATE NEED OF IDEAS FOR NEW PROJECTS IN C# .NET Pin
KFC MANAGER 694-Jun-18 6:25
KFC MANAGER 694-Jun-18 6:25 
AnswerRe: IN DESPERATE NEED OF IDEAS FOR NEW PROJECTS IN C# .NET Pin
OriginalGriff4-Jun-18 6:34
mveOriginalGriff4-Jun-18 6:34 
Answerre: in desperate need of ideas for new projects in c# .net Pin
BillWoodruff4-Jun-18 6:48
professionalBillWoodruff4-Jun-18 6:48 
AnswerRe: IN DESPERATE NEED OF IDEAS FOR NEW PROJECTS IN C# .NET Pin
Gerry Schmitz5-Jun-18 5:18
mveGerry Schmitz5-Jun-18 5:18 
AnswerRe: IN DESPERATE NEED OF IDEAS FOR NEW PROJECTS IN C# .NET Pin
#realJSOP6-Jun-18 3:32
mve#realJSOP6-Jun-18 3:32 
QuestionJSON problem with backslash through REST service Pin
Member 90507314-Jun-18 5:30
Member 90507314-Jun-18 5:30 
AnswerRe: JSON problem with backslash through REST service Pin
Richard Deeming4-Jun-18 5:53
mveRichard Deeming4-Jun-18 5:53 
Questionsend sms from c# windows application Pin
Mohamed Fahad M2-Jun-18 21:53
Mohamed Fahad M2-Jun-18 21:53 
AnswerRe: send sms from c# windows application Pin
OriginalGriff2-Jun-18 22:14
mveOriginalGriff2-Jun-18 22:14 
QuestionC sharp code for Objective and subjective CBT Exam Pin
Member 1293991431-May-18 0:39
Member 1293991431-May-18 0:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.