Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 13th, 2012  |  syntax: None  |  size: 1.58 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Getting items from an MFC list control from .NET
  2. [DllImport( "user32.dll", SetLastError = true )]
  3.         public static extern uint GetDlgItemText( IntPtr hDlg, int nIDDlgItem, [Out] StringBuilder lpString, int nMaxCount );
  4.        
  5. [DllImport( "User32", SetLastError = true )]
  6.         public static extern IntPtr GetDlgItem( IntPtr hwndParent, int ItemId );
  7.        
  8. private string GetSelectedItem()
  9. {
  10.     string item = null;
  11.  
  12.     IntPtr pStringBuffer = Marshal.AllocHGlobal(2048);
  13.     IntPtr pItemBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LVITEM)));
  14.  
  15.     int selectedItemIndex = SendMessage(base.Handle, LVM_GETNEXTITEM, (IntPtr)(-1), (IntPtr)LVNI_SELECTED).ToInt32();
  16.     if (selectedItemIndex > -1)
  17.     {
  18.         LVITEM lvi = new LVITEM();
  19.         lvi.cchTextMax = 1024;
  20.         lvi.pszText = pStringBuffer;
  21.         Marshal.StructureToPtr(lvi, pItemBuffer, false);
  22.         int numChars = SendMessage(base.Handle, LVM_GETITEMTEXT, (IntPtr)selectedItemIndex, pItemBuffer).ToInt32();
  23.         if (numChars > 0)
  24.         {
  25.             item = Marshal.PtrToStringUni(lvi.pszText, numChars);
  26.         }
  27.     }
  28.  
  29.     Marshal.FreeHGlobal(pStringBuffer);
  30.     Marshal.FreeHGlobal(pItemBuffer);
  31.  
  32.     return item;
  33. }
  34.  
  35. struct LVITEM
  36. {
  37.     public int mask;
  38.     public int iItem;
  39.     public int iSubItem;
  40.     public int state;
  41.     public int stateMask;
  42.     public IntPtr pszText;
  43.     public int cchTextMax;
  44.     public int iImage;
  45.     public IntPtr lParam;
  46.     public int iIndent;
  47.     public int iGroupId;
  48.     int cColumns; // tile view columns
  49.     public IntPtr puColumns;
  50.     public IntPtr piColFmt;
  51.     public int iGroup;
  52.  
  53. }