/// <summary> /// コピーの進捗状況通知イベント /// </summary> void copyObject_ProgressChanged( object s, PInvoke.Win32API.CopyProgressEventArgs e ) { //中断ボタン押下メッセージ受付のためメッセージ処理 //本当はコピーをスレッド化してUI操作の受付をしておくべき。 this.DoEvents(); //0除算対応して進捗率の取得 var progresspar = e.TotalFileSize > 0 ? ( (decimal)e.TotalBytesTransferred / (decimal)e.TotalFileSize ) * (decimal)100 : (decimal)0; Dispatcher.Invoke(new Action(() => { //プログレスバー更新 this.progressBar1.Value = (int)progresspar; })); //中断処理判定 if( _Stop ) { e.CopyProgressResult = PInvoke.Win32API.CopyProgressResult.PROGRESS_STOP; } }
public override bool MouseIsOverListView() { return(ListViewController != null && PInvoke.WindowFromPoint(Control.MousePosition) == ListViewController.Handle); }
public override bool HasFocus() { return(ListViewController != null && PInvoke.GetFocus() == ListViewController.Handle); }
public void DrawBlocks() { if (!Volume.BitmapLoaded) { return; } //if (Drawing.IsDrawing) // return; // Wait until width is not NaN while (double.IsNaN(GetWidth())) { } ThreadSafeWidth = GetWidth(); int currentX = 0; int currentY = 0; uint BytesReturned = 0; uint BitmapSize = (65536 + 2 * sizeof(ulong)); int err; ulong currLcn = 0; ulong?lastLcn = 0; ulong lastCluster = 0; ulong?cluster = null; ulong?cluster2 = null; ulong clusterCount = 0; ulong clusterCount2 = 0; ulong numFree = 0; ulong numFree2 = 0; ulong numFree3 = 0; int[] BitShift = { 1, 2, 4, 8, 16, 32, 64, 128 }; ulong Max = Utils.Min(Volume.PartInfo.ClusterCount, 8 * 65536); do { if (_cancellationTokenSource.IsCancellationRequested) { break; } GCHandle handle = GCHandle.Alloc(currLcn, GCHandleType.Pinned); var CurrentLCNPtr = handle.AddrOfPinnedObject(); var pDest = Marshal.AllocHGlobal((int)BitmapSize); PInvoke.DeviceIoControl( Volume.Handle, PInvoke.FSConstants.FSCTL_GET_VOLUME_BITMAP, CurrentLCNPtr, (uint)Marshal.SizeOf(currLcn), pDest, BitmapSize, ref BytesReturned, IntPtr.Zero); err = Marshal.GetLastWin32Error(); if (err != PInvoke.ERROR_MORE_DATA && err != PInvoke.ERROR_HANDLE_EOF) { break; } PInvoke.VOLUME_BITMAP_BUFFER BitmapBuffer = new PInvoke.VOLUME_BITMAP_BUFFER(pDest, (int)BitmapSize); ulong i; for (i = 0; i < Max; i++) { if (_cancellationTokenSource.IsCancellationRequested) { break; } if ((BitmapBuffer.Buffer[i / 8] & BitShift[i % 8]) > 0) { // Cluster is used if (cluster.HasValue) { if ((lastLcn.HasValue) && cluster.Value == lastLcn.Value) { lastLcn = null; } else { numFree2 += numFree; //cFreeSpaceGaps++; if (BlockSize == 1) { DrawBlocks(cluster2.Value, cluster2.Value + numFree2, 0xFFFFFF); } lastCluster = cluster2.Value + numFree2; lastLcn = cluster; numFree = 0; numFree2 = 0; clusterCount2 = 0; cluster = null; cluster2 = null; } } } else { // Cluster is free if (!cluster.HasValue) { cluster = currLcn + i; if (BlockSize == 1) { DrawBlocks(lastCluster, cluster.Value, ColFile); } cluster2 = cluster; numFree = 1; numFree3++; } else { numFree++; numFree3++; } } clusterCount++; if (clusterCount == clustersPerBlock) { clusterCount2 += clustersPerBlock; } // prevent drawing as one big block if (clusterCount2 >= clustersPerLine && BlockSize == 1) { if (cluster2.HasValue && numFree > clustersPerLine) { DrawBlocks(cluster2.Value, cluster2.Value + numFree, ColWhite); } else if (numFree == 0) { DrawBlocks(currLcn + i - clustersPerLine, currLcn + i, ColFile); } clusterCount2 = 0; } // draw the shit if (clusterCount >= clustersPerBlock) { if (BlockSize != 1) { DrawNoBlockBound(currentX, currentY); // just make sure all is new if (numFree3 >= clustersPerBlock) { DrawBlockAt(currentX, currentY, ColWhite); } else if (numFree3 == 0) { DrawBlockAt(currentX, currentY, ColFile); } else if (numFree3 >= (clustersPerBlock / colorSteps) * 4) { DrawBlockAt(currentX, currentY, ColF5); } else if (numFree3 >= (clustersPerBlock / colorSteps) * 3) { DrawBlockAt(currentX, currentY, ColF4); } else if (numFree3 >= (clustersPerBlock / colorSteps) * 2) { DrawBlockAt(currentX, currentY, ColF3); } else if (numFree3 >= (clustersPerBlock / colorSteps)) { DrawBlockAt(currentX, currentY, ColF2); } else { DrawBlockAt(currentX, currentY, ColF1); } /* * else * for (j=colorsteps-1; j>0; j--) * if (numFree3 >= (int)(clustersPB/colorsteps)*j || j==1) { * DrawBlockAt(x, y, LighterVal(ColFile, 256/(colorsteps-j+1)-(colorsteps-j) )); * break; * } */ currentX += BlockSize; if (currentX > (int)(ThreadSafeWidth - BlockSize)) { // move to next y-line currentX = 0; currentY += BlockSize; } numFree3 = 0; } clusterCount = 0; } } // for all clusters in this pair // Move to the next block currLcn = BitmapBuffer.StartingLcn.QuadPart + i; } while ((err == PInvoke.ERROR_MORE_DATA) && (currLcn < Volume.PartInfo.ClusterCount)); if (clusterCount > 0) { //cFreeSpaceGaps++; // draw last cluster if (BlockSize > 1) { DrawNoBlockBound(currentX, currentY); if (numFree3 == clusterCount) { DrawBlockAt(currentX, currentY, ColWhite); } else { if (numFree3 > 0) { uint col = Utils.LighterVal(ColFile, (int)(((float)((int)(clustersPerBlock - (clustersPerBlock - numFree3))) / (int)clustersPerBlock) * 255.0)); DrawBlockAt(currentX, currentY, col); } else { DrawBlockAt(currentX, currentY, ColFile); } } } else { if (cluster2.HasValue) { if (numFree > 0) { DrawBlocks(cluster2.Value, cluster2.Value + numFree, ColWhite); } else { DrawBlocks(lastCluster, currLcn, ColFile); } } } } // Update window if (Dispatcher.Thread != Thread.CurrentThread) { Dispatcher.Invoke(() => draw.InvalidateVisual()); } else { draw.InvalidateVisual(); } }
public Address(IntPtr pidl) { this.ITEMIDLIST = PInvoke.GetIDListData(pidl); this.Path = null; }
private static ImageData LoadThumbnail2(string path, DateTime dtLastWriteTime, out Size sizeRaw, out Size sizeActual, out string toolTipText, out bool fCached) { sizeRaw = sizeActual = Size.Empty; toolTipText = null; fCached = false; IntPtr zero = IntPtr.Zero; IShellFolder ppv = null; object obj2 = null; try { IntPtr ptr3; zero = PInvoke.ILCreateFromPath(path); if ((zero != IntPtr.Zero) && (PInvoke.SHBindToParent(zero, ExplorerGUIDs.IID_IShellFolder, out ppv, out ptr3) == 0)) { uint rgfReserved = 0; Guid riid = ExplorerGUIDs.IID_IExtractImage; IntPtr[] apidl = new IntPtr[] { ptr3 }; if (ppv.GetUIObjectOf(IntPtr.Zero, 1, apidl, ref riid, ref rgfReserved, out obj2) == 0) { IntPtr ptr2; IExtractImage image = (IExtractImage)obj2; StringBuilder pszPathBuffer = new StringBuilder(260); int pdwPriority = 0; Size prgSize = new Size(QTUtility.PreviewMaxWidth, QTUtility.PreviewMaxHeight); int pdwFlags = 0x60; if (((image.GetLocation(pszPathBuffer, pszPathBuffer.Capacity, ref pdwPriority, ref prgSize, 0x18, ref pdwFlags) == 0) && (image.Extract(out ptr2) == 0)) && (ptr2 != IntPtr.Zero)) { Bitmap bmp = Image.FromHbitmap(ptr2); Size size = bmp.Size; sizeRaw = sizeActual = size; ImageData data = new ImageData(bmp, null, path, dtLastWriteTime, size, size); data.Thumbnail = true; try { toolTipText = data.TooltipText = ShellMethods.GetShellInfoTipText(zero, false); } catch { } return(data); } } } } catch (Exception exception) { QTUtility2.MakeErrorLog(exception, null); } finally { if (zero != IntPtr.Zero) { PInvoke.CoTaskMemFree(zero); } if (ppv != null) { Marshal.ReleaseComObject(ppv); } if (obj2 != null) { Marshal.ReleaseComObject(obj2); } } return(null); }
public unsafe void XferData(byte[][] cBufs, byte[][] xBufs, byte[][] oLaps, ISO_PKT_INFO[][] pktsInfo, GCHandle[] handleOverlap) { int k = 0; int len = 0; Successes = 0; Failures = 0; XferBytes = 0; t1 = DateTime.Now; long nIteration = 0; CyUSB.OVERLAPPED ovData = new CyUSB.OVERLAPPED(); DisplayPacketInfo dp = new DisplayPacketInfo((int x, int y, double z) => UpdatePackageInfo(x, y, z)); for (; bRunning;) { nIteration++; // WaitForXfer unsafe { //fixed (byte* tmpOvlap = oLaps[k]) { ovData = (CyUSB.OVERLAPPED)Marshal.PtrToStructure(handleOverlap[k].AddrOfPinnedObject(), typeof(CyUSB.OVERLAPPED)); if (!BulkInEndPoint.WaitForXfer(ovData.hEvent, 500)) { BulkInEndPoint.Abort(); PInvoke.WaitForSingleObject(ovData.hEvent, 500); } } } // FinishDataXfer int FirstPackage; int LastPackage = 0; int PkgLength; if (BulkInEndPoint.FinishDataXfer(ref cBufs[k], ref xBufs[k], ref len, ref oLaps[k])) { XferBytes += len; //if(xBufs[k] != null) if (len != 0) { byte[] DataToFile = new byte[len]; Array.Copy(xBufs[k], DataToFile, len); //AcqDataBuffer.SetData(DataToFile); ThreadData.Add(DataToFile); FirstPackage = DataToFile[0] + (DataToFile[1] << 8) + (DataToFile[2] << 16) + (DataToFile[3] << 24); PkgLength = DataToFile.Length; LastPackage = DataToFile[PkgLength - 4] + (DataToFile[PkgLength - 3] << 8) + (DataToFile[PkgLength - 2] << 16) + (DataToFile[PkgLength - 1] << 24); } Successes++; } else { Failures++; } // Re-submit this buffer into the queue len = BufSz; if (BulkInEndPoint.BeginDataXfer(ref cBufs[k], ref xBufs[k], ref len, ref oLaps[k]) == false) { Failures++; } Thread.Sleep(10); k++; if (k == QueueSz) // Only update displayed stats once each time through the queue { k = 0; t2 = DateTime.Now; elapsed = t2 - t1; xferRate = XferBytes / elapsed.TotalMilliseconds; xferRate = xferRate / (1000.0); Dispatcher.Invoke(dp, (int)Successes, (int)Failures, (double)xferRate); // Call StatusUpdate() in the main thread //if (bRunning == true) this.Invoke(updateUI); // For small QueueSz or PPX, the loop is too tight for UI thread to ever get service. // Without this, app hangs in those scenarios. Thread.Sleep(0); } Thread.Sleep(0); } // End infinite loop // Let's recall all the queued buffer and abort the end point. BulkInEndPoint.Abort(); //AcqDataBuffer.SetDataDone(); ThreadData.CompleteAdding(); }
public static void Initialize(bool skipServer = false) { uint desktopPID; PInvoke.GetWindowThreadProcessId(WindowUtils.GetShellTrayWnd(), out desktopPID); isServer = desktopPID == PInvoke.GetCurrentProcessId(); const string PipeName = "QTTabBarPipe"; string address = "net.pipe://localhost/" + PipeName + desktopPID; Thread thread = null; // WFC channels should never be opened on any thread that has a message loop! // Otherwise reentrant calls will deadlock, for some reason. // So, create a new thread and open the channels there. thread = new Thread(() => { if (isServer && !skipServer) { serviceHost = new ServiceHost( typeof(CommService), new Uri[] { new Uri(address) }); serviceHost.AddServiceEndpoint( typeof(ICommService), new NetNamedPipeBinding(NetNamedPipeSecurityMode.None) { ReceiveTimeout = TimeSpan.MaxValue, ReaderQuotas = { MaxArrayLength = int.MaxValue }, MaxBufferSize = int.MaxValue, MaxReceivedMessageSize = int.MaxValue, }, new Uri(address)); serviceHost.Open(); } commClient = new DuplexClient(new InstanceContext(new CommClient()), new NetNamedPipeBinding(NetNamedPipeSecurityMode.None) { ReceiveTimeout = TimeSpan.MaxValue, ReaderQuotas = { MaxArrayLength = int.MaxValue }, MaxBufferSize = int.MaxValue, MaxReceivedMessageSize = int.MaxValue, }, new EndpointAddress(address)); try { commClient.Open(); commClient.Channel.Subscribe(); using (new Keychain(rwLockTabBar, false)) { foreach (IntPtr handle in sdTabHandles.Keys) { commClient.Channel.PushInstance(handle); } } } catch (EndpointNotFoundException) { } lock (thread) { Monitor.Pulse(thread); } // Yes, we can just let the thread die here. }); thread.Start(); lock (thread) { Monitor.Wait(thread); } }
/// <summary> /// Gets drive bitmap /// </summary> /// <returns></returns> public bool GetBitmap() { Int64 StartingLCN = 0; uint BytesReturned = 0; GCHandle handle = GCHandle.Alloc(StartingLCN, GCHandleType.Pinned); var StartingLCNPtr = handle.AddrOfPinnedObject(); //BitmapSize = (uint)Marshal.SizeOf(typeof(PInvoke.VOLUME_BITMAP_BUFFER)) + 4; uint BitmapSize = 28; var pDest = Marshal.AllocHGlobal((int)BitmapSize); var Result = PInvoke.DeviceIoControl( Handle, PInvoke.FSConstants.FSCTL_GET_VOLUME_BITMAP, StartingLCNPtr, (uint)Marshal.SizeOf(StartingLCN), pDest, BitmapSize, ref BytesReturned, IntPtr.Zero); // Bad result? if (Result == false && Marshal.GetLastWin32Error() != PInvoke.ERROR_MORE_DATA) { Marshal.FreeHGlobal(pDest); return(false); } var Bitmap = new PInvoke.VOLUME_BITMAP_BUFFER(pDest, false); BitmapSize = (uint)Marshal.SizeOf(typeof(PInvoke.VOLUME_BITMAP_BUFFER)) + ((uint)Bitmap.BitmapSize.QuadPart / 8) + 1; pDest = Marshal.ReAllocHGlobal(pDest, (IntPtr)BitmapSize); Result = PInvoke.DeviceIoControl( Handle, PInvoke.FSConstants.FSCTL_GET_VOLUME_BITMAP, StartingLCNPtr, (uint)Marshal.SizeOf(StartingLCN), pDest, BitmapSize, ref BytesReturned, IntPtr.Zero); if (Result == false) { Debug.WriteLine("Couldn't properly read volume bitmap"); Marshal.FreeHGlobal(pDest); return(false); } Bitmap = new PInvoke.VOLUME_BITMAP_BUFFER(pDest, true); /* * BitmapSize = (uint)Marshal.SizeOf(typeof(PInvoke.VOLUME_BITMAP_BUFFER)) + ((uint)Bitmap.BitmapSize.QuadPart / 8) + 1; */ PartInfo.ClusterCount = Bitmap.BitmapSize.QuadPart; BitmapDetail = Bitmap.Buffer; Marshal.FreeHGlobal(pDest); return(true); }
private static string FetchMessage(string msgDll, uint messageID, string [] replacementStrings) { // http://msdn.microsoft.com/library/en-us/debug/base/formatmessage.asp // http://msdn.microsoft.com/msdnmag/issues/02/08/CQA/ // http://msdn.microsoft.com/netframework/programming/netcf/cffaq/default.aspx IntPtr msgDllHandle = PInvoke.LoadLibraryEx(msgDll, IntPtr.Zero, LoadFlags.LibraryAsDataFile); if (msgDllHandle == IntPtr.Zero) { // TODO: write warning return(null); } IntPtr lpMsgBuf = IntPtr.Zero; IntPtr [] arguments = new IntPtr [replacementStrings.Length]; try { for (int i = 0; i < replacementStrings.Length; i++) { arguments [i] = Marshal.StringToHGlobalAuto( replacementStrings [i]); } int ret = PInvoke.FormatMessage(FormatMessageFlags.ArgumentArray | FormatMessageFlags.FromHModule | FormatMessageFlags.AllocateBuffer, msgDllHandle, messageID, 0, ref lpMsgBuf, 0, arguments); if (ret != 0) { string sRet = Marshal.PtrToStringAuto(lpMsgBuf); lpMsgBuf = PInvoke.LocalFree(lpMsgBuf); // remove trailing whitespace (CRLF) return(sRet.TrimEnd(null)); } else { int err = Marshal.GetLastWin32Error(); if (err == MESSAGE_NOT_FOUND) { // do not consider this a failure (or even warning) as // multiple message resource DLLs may have been configured // and as such we just need to try the next library if // the current one does not contain a message for this // ID } else { // TODO: report warning } } } finally { // release unmanaged memory allocated for replacement strings for (int i = 0; i < arguments.Length; i++) { IntPtr argument = arguments [i]; if (argument != IntPtr.Zero) { Marshal.FreeHGlobal(argument); } } PInvoke.FreeLibrary(msgDllHandle); } return(null); }
private static Rect GetVirtualScreen() { var size = new Size(PInvoke.GetSystemMetrics(SM_CXSCREEN), PInvoke.GetSystemMetrics(SM_CYSCREEN)); return(new Rect(0, 0, size.Width, size.Height)); }
public void isigopenTest() { var ret = PInvoke.isigopen(string.Empty, null, 0); Assert.AreEqual(ret, -1); // no input file // Testing for invalid header file. string file = "data/invalid"; ret = PInvoke.isigopen(file, null, 0); Assert.IsTrue(ret == -2); // Testing for real data file = "data/100s"; ret = PInvoke.isigopen(file, null, 1); // Number of signals > 1 Assert.IsTrue(ret == 0); // Two signals in the record, this syntax will return the number of available signals var numberOfSignals = PInvoke.isigopen(file, null, 0); Assert.AreEqual(numberOfSignals, 2); // Dealing with real data. var s = new Signal[numberOfSignals]; ret = PInvoke.isigopen(file, s, 2); Assert.AreEqual(ret, 2); // Check for results : Signal 100s Assert.AreEqual("100s.dat", s[0].FileName); Assert.AreEqual("100s.dat", s[1].FileName); Assert.AreEqual("MLII", s[0].Description); Assert.AreEqual("V5", s[1].Description); Assert.AreEqual(21600, s[0].NumberOfSamples); Assert.AreEqual(21600, s[1].NumberOfSamples); Assert.AreEqual(SignalStorageFormat.Sf212Bit, s[0].Format); Assert.AreEqual(SignalStorageFormat.Sf212Bit, s[1].Format); Assert.AreEqual(1, s[0].SamplesPerFrame); Assert.AreEqual(1, s[1].SamplesPerFrame); Assert.AreEqual(Gain.DefaultGain, s[0].Gain); Assert.AreEqual(Gain.DefaultGain, s[1].Gain); Assert.AreEqual(200.0, s[0].Gain.Value); Assert.AreEqual(200.0, s[1].Gain.Value); Assert.AreEqual(11, s[0].AdcResolution); Assert.AreEqual(11, s[1].AdcResolution); Assert.AreEqual(1024, s[0].AdcZero); Assert.AreEqual(1024, s[1].AdcZero); Assert.AreEqual(1024, s[0].Baseline); Assert.AreEqual(1024, s[1].Baseline); Assert.AreEqual(995, s[0].InitValue); Assert.AreEqual(1011, s[1].InitValue); Assert.AreEqual(0, s[0].Group); Assert.AreEqual(0, s[1].Group); Assert.AreEqual(0, s[0].BlockSize); Assert.AreEqual(0, s[1].BlockSize); Assert.AreEqual(21537, s[0].CheckSum); Assert.AreEqual(-3962, s[1].CheckSum); PInvoke.wfdbquit(); }
public void TestFixtureTearDown() { PInvoke.wfdbquit(); }
protected override bool OnShellViewNotify(NMHDR nmhdr, ref Message msg) { // Process WM.NOTIFY. These are all notifications from the // SysListView32 control. We will not get ANY of these on // Windows 7, which means every single one of them has to // have an alternative somewhere for the ItemsView control, // or it's not going to happen. switch (nmhdr.code) { case -12: // NM_CUSTOMDRAW // This is for drawing alternating row colors. I doubt // very much we'll find an alternative for this... return(HandleCustomDraw(ref msg)); case LVN.ITEMCHANGED: { // There are two things happening here. // 1. Notify plugins of selection changing: Handled through // undocumented WM_USER+163 message // 2. Redraw for Full Row Select: Not happening /* * // TODO * * IntPtr ptr; * if(QTUtility.instanceManager.TryGetButtonBarHandle(this.hwndExplorer, out ptr)) { * QTUtility2.SendCOPYDATASTRUCT(ptr, (IntPtr)13, null, (IntPtr)GetItemCount()); * } */ bool flag = !QTUtility.IsXP && QTUtility.CheckConfig(Settings.ToggleFullRowSelect); NMLISTVIEW nmlistview2 = (NMLISTVIEW)Marshal.PtrToStructure(msg.LParam, typeof(NMLISTVIEW)); if (nmlistview2.uChanged == 8 /*LVIF_STATE*/) { uint num5 = nmlistview2.uNewState & LVIS.SELECTED; uint num6 = nmlistview2.uOldState & LVIS.SELECTED; uint num7 = nmlistview2.uNewState & LVIS.DROPHILITED; uint num8 = nmlistview2.uOldState & LVIS.DROPHILITED; uint num9 = nmlistview2.uNewState & LVIS.CUT; uint num10 = nmlistview2.uOldState & LVIS.CUT; if (flag) { if (nmlistview2.iItem != -1 && ((num5 != num6) || (num7 != num8) || (num9 != num10)) && ShellBrowser.ViewMode == FVM.DETAILS) { PInvoke.SendMessage(nmlistview2.hdr.hwndFrom, LVM.REDRAWITEMS, (IntPtr)nmlistview2.iItem, (IntPtr)nmlistview2.iItem); } } if (num5 != num6) { OnSelectionChanged(); } } break; } case LVN.INSERTITEM: case LVN.DELETEITEM: case LVN.DELETEALLITEMS: // Handled through undocumented WM_USER+174 message if (!QTUtility.CheckConfig(Settings.NoShowSubDirTips)) { HideSubDirTip(1); } if (QTUtility.CheckConfig(Settings.AlternateRowColors) && (ShellBrowser.ViewMode == FVM.DETAILS)) { PInvoke.InvalidateRect(nmhdr.hwndFrom, IntPtr.Zero, true); } ShellViewController.DefWndProc(ref msg); OnItemCountChanged(); return(true); case LVN.BEGINDRAG: // This won't be necessary it seems. On Windows 7, when you // start to drag, a MOUSELEAVE message is sent, which hides // the SubDirTip anyway. ShellViewController.DefWndProc(ref msg); HideSubDirTip(0xff); break; case LVN.ITEMACTIVATE: { // Handled by catching Double Clicks and Enter keys. Ugh... NMITEMACTIVATE nmitemactivate = (NMITEMACTIVATE)Marshal.PtrToStructure(msg.LParam, typeof(NMITEMACTIVATE)); Keys modKeys = (((nmitemactivate.uKeyFlags & 1) == 1) ? Keys.Alt : Keys.None) | (((nmitemactivate.uKeyFlags & 2) == 2) ? Keys.Control : Keys.None) | (((nmitemactivate.uKeyFlags & 4) == 4) ? Keys.Shift : Keys.None); if (OnItemActivated(modKeys)) { return(true); } break; } case LVN.ODSTATECHANGED: // FullRowSelect doesn't look possible anyway, so whatever. if (!QTUtility.IsXP && QTUtility.CheckConfig(Settings.ToggleFullRowSelect)) { NMLVODSTATECHANGE nmlvodstatechange = (NMLVODSTATECHANGE)Marshal.PtrToStructure(msg.LParam, typeof(NMLVODSTATECHANGE)); if (((nmlvodstatechange.uNewState & 2) == 2) && (ShellBrowser.ViewMode == FVM.DETAILS)) { PInvoke.SendMessage(nmlvodstatechange.hdr.hwndFrom, LVM.REDRAWITEMS, (IntPtr)nmlvodstatechange.iFrom, (IntPtr)nmlvodstatechange.iTo); } } break; case LVN.HOTTRACK: // Handled through WM_MOUSEMOVE. if (QTUtility.CheckConfig(Settings.ShowTooltipPreviews) || !QTUtility.CheckConfig(Settings.NoShowSubDirTips)) { NMLISTVIEW nmlistview = (NMLISTVIEW)Marshal.PtrToStructure(msg.LParam, typeof(NMLISTVIEW)); if (iHotItem != nmlistview.iItem) { OnHotItemChanged(nmlistview.iItem); iHotItem = nmlistview.iItem; } } break; case LVN.KEYDOWN: { // Handled through WM_KEYDOWN. NMLVKEYDOWN nmlvkeydown = (NMLVKEYDOWN)Marshal.PtrToStructure(msg.LParam, typeof(NMLVKEYDOWN)); if (OnKeyDown((Keys)nmlvkeydown.wVKey)) { msg.Result = (IntPtr)1; return(true); } else { return(false); } } case LVN.GETINFOTIP: { // Handled through WM_NOTIFY / TTN_NEEDTEXT NMLVGETINFOTIP nmlvgetinfotip = (NMLVGETINFOTIP)Marshal.PtrToStructure(msg.LParam, typeof(NMLVGETINFOTIP)); return(OnGetInfoTip(nmlvgetinfotip.iItem, GetHotItem() != nmlvgetinfotip.iItem)); // TODO there's got to be a better way. } case LVN.BEGINLABELEDIT: // This is just for file renaming, which there's no need to // mess with in Windows 7. ShellViewController.DefWndProc(ref msg); if (QTUtility.IsXP && !QTUtility.CheckConfig(Settings.ExtWhileRenaming)) { NMLVDISPINFO nmlvdispinfo = (NMLVDISPINFO)Marshal.PtrToStructure(msg.LParam, typeof(NMLVDISPINFO)); if (nmlvdispinfo.item.lParam != IntPtr.Zero) { using (IDLWrapper idl = ShellBrowser.ILAppend(nmlvdispinfo.item.lParam)) { OnFileRename(idl); } } } break; case LVN.ENDLABELEDIT: { // TODO NMLVDISPINFO nmlvdispinfo2 = (NMLVDISPINFO)Marshal.PtrToStructure(msg.LParam, typeof(NMLVDISPINFO)); OnEndLabelEdit(nmlvdispinfo2.item); break; } } return(false); }
private bool HandleCustomDraw(ref Message msg) { // TODO this needs to be cleaned if (QTUtility.CheckConfig(Settings.AlternateRowColors) && (ShellBrowser.ViewMode == FVM.DETAILS)) { NMLVCUSTOMDRAW structure = (NMLVCUSTOMDRAW)Marshal.PtrToStructure(msg.LParam, typeof(NMLVCUSTOMDRAW)); int dwItemSpec = 0; if ((ulong)structure.nmcd.dwItemSpec < Int32.MaxValue) { dwItemSpec = (int)structure.nmcd.dwItemSpec; } switch (structure.nmcd.dwDrawStage) { case CDDS.SUBITEM | CDDS.ITEMPREPAINT: iListViewItemState = (int)PInvoke.SendMessage( ListViewController.Handle, LVM.GETITEMSTATE, structure.nmcd.dwItemSpec, (IntPtr)(LVIS.FOCUSED | LVIS.SELECTED | LVIS.DROPHILITED)); if (!QTUtility.IsXP) { int num4 = lstColumnFMT[structure.iSubItem]; structure.clrTextBk = QTUtility.ShellViewRowCOLORREF_Background; structure.clrText = QTUtility.ShellViewRowCOLORREF_Text; Marshal.StructureToPtr(structure, msg.LParam, false); bool drawingHotItem = (dwItemSpec == GetHotItem()); bool fullRowSel = !QTUtility.CheckConfig(Settings.ToggleFullRowSelect); msg.Result = (IntPtr)(CDRF.NEWFONT); if (structure.iSubItem == 0 && !drawingHotItem) { if (iListViewItemState == 0 && (num4 & 0x600) != 0) { msg.Result = (IntPtr)(CDRF.NEWFONT | CDRF.NOTIFYPOSTPAINT); } else if (iListViewItemState == LVIS.FOCUSED && !fullRowSel) { msg.Result = (IntPtr)(CDRF.NEWFONT | CDRF.NOTIFYPOSTPAINT); } } if (structure.iSubItem > 0 && (!fullRowSel || !drawingHotItem)) { if (!fullRowSel || (iListViewItemState & (LVIS.SELECTED | LVIS.DROPHILITED)) == 0) { using (Graphics graphics = Graphics.FromHdc(structure.nmcd.hdc)) { if (QTUtility.sbAlternate == null) { QTUtility.sbAlternate = new SolidBrush(QTUtility2.MakeColor(QTUtility.ShellViewRowCOLORREF_Background)); } graphics.FillRectangle(QTUtility.sbAlternate, structure.nmcd.rc.ToRectangle()); } } } } else { msg.Result = (IntPtr)(CDRF.NOTIFYPOSTPAINT); } return(true); case CDDS.SUBITEM | CDDS.ITEMPOSTPAINT: { RECT rc = structure.nmcd.rc; if (QTUtility.IsXP) { rc = PInvoke.ListView_GetItemRect(ListViewController.Handle, dwItemSpec, structure.iSubItem, 2); } else { rc.left += 0x10; } bool flag3 = false; bool flag4 = false; bool flag5 = QTUtility.CheckConfig(Settings.DetailsGridLines); bool flag6 = QTUtility.CheckConfig(Settings.ToggleFullRowSelect) ^ !QTUtility.IsXP; bool flag7 = false; if (QTUtility.IsXP && QTUtility.fSingleClick) { flag7 = (dwItemSpec == GetHotItem()); } LVITEM lvitem = new LVITEM(); lvitem.pszText = Marshal.AllocHGlobal(520); lvitem.cchTextMax = 260; lvitem.iSubItem = structure.iSubItem; lvitem.iItem = dwItemSpec; lvitem.mask = 1; IntPtr ptr3 = Marshal.AllocHGlobal(Marshal.SizeOf(lvitem)); Marshal.StructureToPtr(lvitem, ptr3, false); PInvoke.SendMessage(ListViewController.Handle, LVM.GETITEM, IntPtr.Zero, ptr3); if (QTUtility.sbAlternate == null) { QTUtility.sbAlternate = new SolidBrush(QTUtility2.MakeColor(QTUtility.ShellViewRowCOLORREF_Background)); } using (Graphics graphics2 = Graphics.FromHdc(structure.nmcd.hdc)) { Rectangle rect = rc.ToRectangle(); if (flag5) { rect = new Rectangle(rc.left + 1, rc.top, rc.Width - 1, rc.Height - 1); } graphics2.FillRectangle(QTUtility.sbAlternate, rect); if (QTUtility.IsXP && ((structure.iSubItem == 0) || flag6)) { flag4 = (iListViewItemState & 8) == 8; if ((iListViewItemState != 0) && (((iListViewItemState == 1) && fListViewHasFocus) || (iListViewItemState != 1))) { int width; if (flag6) { width = rc.Width; } else { width = 8 + ((int)PInvoke.SendMessage(ListViewController.Handle, LVM.GETSTRINGWIDTH, IntPtr.Zero, lvitem.pszText)); if (width > rc.Width) { width = rc.Width; } } Rectangle rectangle2 = new Rectangle(rc.left, rc.top, width, flag5 ? (rc.Height - 1) : rc.Height); if (((iListViewItemState & 2) == 2) || flag4) { if (flag4) { graphics2.FillRectangle(SystemBrushes.Highlight, rectangle2); } else if (QTUtility.fSingleClick && flag7) { graphics2.FillRectangle(fListViewHasFocus ? SystemBrushes.HotTrack : SystemBrushes.Control, rectangle2); } else { graphics2.FillRectangle(fListViewHasFocus ? SystemBrushes.Highlight : SystemBrushes.Control, rectangle2); } flag3 = true; } if ((fListViewHasFocus && ((iListViewItemState & 1) == 1)) && !flag6) { ControlPaint.DrawFocusRectangle(graphics2, rectangle2); } } } if (!QTUtility.IsXP && ((iListViewItemState & 1) == 1)) { int num6 = rc.Width; if (!flag6) { num6 = 4 + ((int)PInvoke.SendMessage(ListViewController.Handle, LVM.GETSTRINGWIDTH, IntPtr.Zero, lvitem.pszText)); if (num6 > rc.Width) { num6 = rc.Width; } } Rectangle rectangle = new Rectangle(rc.left + 1, rc.top + 1, num6, flag5 ? (rc.Height - 2) : (rc.Height - 1)); ControlPaint.DrawFocusRectangle(graphics2, rectangle); } } IntPtr zero = IntPtr.Zero; IntPtr hgdiobj = IntPtr.Zero; if (QTUtility.IsXP && QTUtility.fSingleClick) { LOGFONT logfont; zero = PInvoke.GetCurrentObject(structure.nmcd.hdc, 6); PInvoke.GetObject(zero, Marshal.SizeOf(typeof(LOGFONT)), out logfont); if ((structure.iSubItem == 0) || flag6) { logfont.lfUnderline = ((QTUtility.iIconUnderLineVal == 3) || flag7) ? ((byte)1) : ((byte)0); } else { logfont.lfUnderline = 0; } hgdiobj = PInvoke.CreateFontIndirect(ref logfont); PInvoke.SelectObject(structure.nmcd.hdc, hgdiobj); } PInvoke.SetBkMode(structure.nmcd.hdc, 1); int dwDTFormat = 0x8824; if (QTUtility.IsRTL ? ((lstColumnFMT[structure.iSubItem] & 1) == 0) : ((lstColumnFMT[structure.iSubItem] & 1) == 1)) { if (QTUtility.IsRTL) { dwDTFormat &= -3; } else { dwDTFormat |= 2; } rc.right -= 6; } else if (structure.iSubItem == 0) { rc.left += 2; rc.right -= 2; } else { rc.left += 6; } if (flag3) { PInvoke.SetTextColor(structure.nmcd.hdc, QTUtility2.MakeCOLORREF((fListViewHasFocus || flag4) ? SystemColors.HighlightText : SystemColors.WindowText)); } else { PInvoke.SetTextColor(structure.nmcd.hdc, QTUtility.ShellViewRowCOLORREF_Text); } PInvoke.DrawTextExW(structure.nmcd.hdc, lvitem.pszText, -1, ref rc, dwDTFormat, IntPtr.Zero); Marshal.FreeHGlobal(lvitem.pszText); Marshal.FreeHGlobal(ptr3); msg.Result = IntPtr.Zero; if (zero != IntPtr.Zero) { PInvoke.SelectObject(structure.nmcd.hdc, zero); } if (hgdiobj != IntPtr.Zero) { PInvoke.DeleteObject(hgdiobj); } return(true); } case CDDS.ITEMPREPAINT: if ((dwItemSpec % 2) == 0) { msg.Result = (IntPtr)0x20; return(true); } msg.Result = IntPtr.Zero; return(false); case CDDS.PREPAINT: { HDITEM hditem = new HDITEM(); hditem.mask = 4; IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(hditem)); Marshal.StructureToPtr(hditem, ptr, false); IntPtr hWnd = PInvoke.SendMessage(ListViewController.Handle, LVM.GETHEADER, IntPtr.Zero, IntPtr.Zero); int num2 = (int)PInvoke.SendMessage(hWnd, 0x1200, IntPtr.Zero, IntPtr.Zero); if (lstColumnFMT == null) { lstColumnFMT = new List <int>(); } else { lstColumnFMT.Clear(); } for (int i = 0; i < num2; i++) { PInvoke.SendMessage(hWnd, 0x120b, (IntPtr)i, ptr); hditem = (HDITEM)Marshal.PtrToStructure(ptr, typeof(HDITEM)); lstColumnFMT.Add(hditem.fmt); } Marshal.FreeHGlobal(ptr); fListViewHasFocus = ListViewController.Handle == PInvoke.GetFocus(); msg.Result = (IntPtr)0x20; return(true); } } } return(false); }
protected override bool HandleCursorLoop(Keys key) { int focusedIdx = ShellBrowser.GetFocusedIndex(); int itemCount = ShellBrowser.GetItemCount(); int selectMe = -1; int viewMode = ShellBrowser.ViewMode; if (viewMode == FVM.TILE && QTUtility.IsXP) { viewMode = FVM.ICON; } switch (viewMode) { case FVM.CONTENT: case FVM.DETAILS: case FVM.TILE: if (key == Keys.Up && focusedIdx == 0) { selectMe = itemCount - 1; } else if (key == Keys.Down && focusedIdx == itemCount - 1) { selectMe = 0; } break; case FVM.ICON: case FVM.SMALLICON: case FVM.THUMBNAIL: case FVM.LIST: Keys KeyNextItem, KeyPrevItem, KeyNextPage, KeyPrevPage; IntPtr MsgNextPage, MsgPrevPage; if (viewMode == FVM.LIST) { KeyNextItem = Keys.Down; KeyPrevItem = Keys.Up; KeyNextPage = Keys.Right; KeyPrevPage = Keys.Left; MsgNextPage = (IntPtr)LVNI.TORIGHT; MsgPrevPage = (IntPtr)LVNI.TOLEFT; } else { KeyNextItem = Keys.Right; KeyPrevItem = Keys.Left; KeyNextPage = Keys.Down; KeyPrevPage = Keys.Up; MsgNextPage = (IntPtr)LVNI.BELOW; MsgPrevPage = (IntPtr)LVNI.ABOVE; } int nextPageIdx = (int)PInvoke.SendMessage(Handle, LVM.GETNEXTITEM, (IntPtr)focusedIdx, MsgNextPage); if (nextPageIdx == -1 || nextPageIdx == focusedIdx) { nextPageIdx = (int)PInvoke.SendMessage(Handle, LVM.GETNEXTITEM, (IntPtr)focusedIdx, MsgPrevPage); } else if (QTUtility.IsXP) { int testIdx = (int)PInvoke.SendMessage(Handle, LVM.GETNEXTITEM, (IntPtr)nextPageIdx, MsgPrevPage); if (testIdx != focusedIdx) { nextPageIdx = (int)PInvoke.SendMessage(Handle, LVM.GETNEXTITEM, (IntPtr)focusedIdx, MsgPrevPage); } } if (nextPageIdx == -1 || nextPageIdx == focusedIdx) { if (key == KeyNextItem) { if (focusedIdx == itemCount - 1) { selectMe = 0; } else { RECT thisRect = GetItemRect(focusedIdx); RECT nextRect = GetItemRect(focusedIdx + 1); if (viewMode == FVM.LIST) { if (nextRect.top < thisRect.top) { selectMe = 0; } } else if (nextRect.left < thisRect.left) { selectMe = 0; } } } else if (key == KeyPrevItem && focusedIdx == 0) { selectMe = itemCount - 1; } else if (key == KeyNextPage || key == KeyPrevPage) { if (QTUtility.IsXP) { return(true); } } } else { int pageCount = Math.Abs(focusedIdx - nextPageIdx); int page = focusedIdx % pageCount; if (key == KeyNextItem && (page == pageCount - 1 || focusedIdx == itemCount - 1)) { selectMe = focusedIdx - page; } else if (key == KeyPrevItem && page == 0) { selectMe = Math.Min(focusedIdx + pageCount - 1, itemCount - 1); } else if (key == KeyNextPage && focusedIdx + pageCount >= itemCount) { selectMe = page; } else if (key == KeyPrevPage && focusedIdx < pageCount) { int x = itemCount - focusedIdx - 1; selectMe = x - x % pageCount + focusedIdx; } } break; } if (selectMe >= 0) { SetRedraw(false); ShellBrowser.SelectItem(selectMe); PInvoke.SendMessage(Handle, LVM.REDRAWITEMS, (IntPtr)focusedIdx, (IntPtr)focusedIdx); SetRedraw(true); return(true); } else { return(false); } }
public override bool GetPartitionDetails() { uint BytesRead; ulong FATSize; IntPtr BootSectorPtr = Marshal.AllocHGlobal(512); NativeOverlapped Overlapped = new NativeOverlapped(); var result = PInvoke.ReadFile(Volume.Handle, BootSectorPtr, 512, out BytesRead, ref Overlapped); if (!result) { Debug.WriteLine("Error #{0} occurred trying to read volume {1}", Marshal.GetLastWin32Error(), Volume.RootPath); return(false); } var BootSector = new PInvoke.FATBootSector(BootSectorPtr); if (BootSector.Signature != 0xAA55 || (((BootSector.BS_jmpBoot[0] != 0xEB) || (BootSector.BS_jmpBoot[2] != 0x90)) && (BootSector.BS_jmpBoot[0] != 0xE9))) { Debug.WriteLine("Volume is not a valid FAT partition"); return(false); } // Fetch values from the bootblock and determine what FAT this is, FAT12, FAT16, or FAT32. BytesPerSector = BootSector.BytesPerSector; if (BytesPerSector == 0) { Debug.WriteLine("This is not a FAT disk (BytesPerSector is zero)."); return(false); } SectorsPerCluster = BootSector.SectorsPerCluster; if (SectorsPerCluster == 0) { Debug.WriteLine("This is not a FAT disk (SectorsPerCluster is zero)."); return(false); } TotalSectors = BootSector.TotalSectors16; if (TotalSectors == 0) { TotalSectors = BootSector.TotalSectors32; } RootDirSectors = (ulong)((BootSector.RootEntries * 32) + (BootSector.BytesPerSector - 1)) / BootSector.BytesPerSector; uint SectorsPerFAT = BootSector.SectorsPerFAT; if (SectorsPerFAT == 0) { SectorsPerFAT = BootSector.FAT1632Info.FAT32_SectorsPerFAT32; } FirstDataSector = BootSector.ReservedSectors + (BootSector.NumberOfFATs * SectorsPerFAT) + RootDirSectors; DataSector = TotalSectors - (BootSector.ReservedSectors + (BootSector.NumberOfFATs * SectorsPerFAT) + RootDirSectors); ClusterCount = DataSector / BootSector.SectorsPerCluster; if (ClusterCount < 4085) { Type = FATTypes.FAT12; Debug.WriteLine("This is a FAT12 disk."); } else if (ClusterCount < 65525) { Type = FATTypes.FAT16; Debug.WriteLine("This is a FAT16 disk."); } else { Type = FATTypes.FAT32; Debug.WriteLine("This is a FAT32 disk."); } BytesPerCluster = BytesPerSector * SectorsPerCluster; TotalClusters = (uint)ClusterCount; Debug.WriteLine(" OEMName: {0}", BootSector.BS_OEMName); Debug.WriteLine(" BytesPerSector: {0:d}", BytesPerSector); Debug.WriteLine(" TotalSectors: {0:d}", TotalSectors); Debug.WriteLine(" SectorsPerCluster: {0:d}", SectorsPerCluster); Debug.WriteLine(" RootDirSectors: {0:d}", RootDirSectors); Debug.WriteLine(" FATSz: {0:d}", SectorsPerFAT); Debug.WriteLine(" FirstDataSector: {0:d}", FirstDataSector); Debug.WriteLine(" DataSec: {0:d}", DataSector); Debug.WriteLine(" CountofClusters: {0:d}", ClusterCount); Debug.WriteLine(" ReservedSectors: {0:d}", BootSector.ReservedSectors); Debug.WriteLine(" NumberFATs: {0:d}", BootSector.NumberOfFATs); Debug.WriteLine(" RootEntriesCount: {0:d}", BootSector.RootEntries); Debug.WriteLine(" MediaType: {0:X}", BootSector.MediaDescriptor); Debug.WriteLine(" SectorsPerTrack: {0:d}", BootSector.SectorsPerTrack); Debug.WriteLine(" NumberOfHeads: {0:d}", BootSector.Heads); Debug.WriteLine(" HiddenSectors: {0:d}", BootSector.HiddenSectors); if (Type != FATTypes.FAT32) { Debug.WriteLine(" BS_DrvNum: {0:d}", BootSector.FAT1632Info.FAT16_LogicalDriveNumber); Debug.WriteLine(" BS_BootSig: {0:d}", BootSector.FAT1632Info.FAT16_ExtendedSignature); Debug.WriteLine(" BS_VolID: {0:d}", BootSector.FAT1632Info.FAT16_PartitionSerialNumber); Debug.WriteLine(" VolLab: {0}", BootSector.FAT1632Info.FAT16_VolumeName); Debug.WriteLine(" FilSysType: {0}", BootSector.FAT1632Info.FAT16_FSType); } else { Debug.WriteLine(" FATSz32: {0:d}", BootSector.FAT1632Info.FAT32_SectorsPerFAT32); Debug.WriteLine(" ExtFlags: {0:d}", BootSector.FAT1632Info.FAT32_ExtFlags); Debug.WriteLine(" FSVer: {0:d}", BootSector.FAT1632Info.FAT32_FSVer); Debug.WriteLine(" RootClus: {0:d}", BootSector.FAT1632Info.FAT32_RootDirStart); Debug.WriteLine(" FSInfo: {0:d}", BootSector.FAT1632Info.FAT32_FSInfoSector); Debug.WriteLine(" BkBootSec: {0:d}", BootSector.FAT1632Info.FAT32_BackupBootSector); Debug.WriteLine(" DrvNum: {0:d}", BootSector.FAT1632Info.FAT32_LogicalDriveNumber); Debug.WriteLine(" BootSig: {0:d}", BootSector.FAT1632Info.FAT32_ExtendedSignature); Debug.WriteLine(" VolID: {0:d}", BootSector.FAT1632Info.FAT32_PartitionSerialNumber); Debug.WriteLine(" VolLab: {0}", BootSector.FAT1632Info.FAT32_VolumeName); Debug.WriteLine(" FilSysType: {0}", BootSector.FAT1632Info.FAT32_FSType); } switch (Type) { case FATTypes.FAT12: { FATSize = ClusterCount + 1; break; } case FATTypes.FAT16: { FATSize = (ClusterCount + 1) * 2; break; } case FATTypes.FAT32: { FATSize = (ClusterCount + 1) * 4; break; } default: { FATSize = 0; break; } } if (FATSize % BytesPerSector > 0) { FATSize = FATSize + BytesPerSector - FATSize % BytesPerSector; } PInvoke.LARGE_INTEGER Trans = new PInvoke.LARGE_INTEGER { QuadPart = BootSector.ReservedSectors * BytesPerSector }; IntPtr FATDataPtr = Marshal.AllocHGlobal((int)FATSize); NativeOverlapped nativeOverlapped = new NativeOverlapped { EventHandle = IntPtr.Zero, OffsetLow = (int)Trans.LowPart, OffsetHigh = Trans.HighPart }; PInvoke.ReadFile(Volume.Handle, FATDataPtr, (uint)FATSize, out BytesRead, ref nativeOverlapped); PInvoke.FATData FatData = new PInvoke.FATData(FATDataPtr, Type, FATSize); return(true); }
public bool ScanDirectory(string DirPrefix, ScanCallback Callback, BuildDBInfo UserData) { PInvoke.WIN32_FIND_DATA FindData; var DirIndice = (uint)Directories.Count - 1; var SearchString = DirPrefix + "*"; var FindHandle = PInvoke.FindFirstFile(SearchString, out FindData); if (FindHandle == PInvoke.INVALID_HANDLE_VALUE) { return(false); } do { UInt64 FileSize = ((FindData.nFileSizeHigh << 32) | FindData.nFileSizeLow); FileInfo Info = new FileInfo(FindData.cFileName, DirIndice, FileSize, FindData.dwFileAttributes); SafeFileHandle Handle = null; // DonLL't ever include '.L' and '..' if (Info.Name == "." || Info.Name == "..") { continue; } //Info.FullName = DirPrefix + Info.Name; Info.Clusters = 0; if (GetClusterInfo(Info, ref Handle)) { UInt64 TotalClusters = Info.Fragments.Aggregate <Extent, ulong>(0, (current, ext) => current + ext.Length); Info.Clusters = TotalClusters; } else { Info.Attributes.Unmovable = true; Info.Attributes.Process = false; } if (Info.Attributes.Process) { Info.Attributes.Process = ShouldProcess(Info.Attributes); } // Run the user-defined callback function var CallbackResult = Callback(ref Info, ref Handle, ref UserData); if (!Handle.IsInvalid && !Handle.IsClosed) { Handle.Close(); } if (!CallbackResult) { break; } // If directory, perform recursion if (Info.Attributes.Directory) { var Dir = GetDBDir(Info.DirIndice); Dir += Info.Name; Dir += "\\"; Directories.Add(Dir); ScanDirectory(Dir, Callback, UserData); } } while (PInvoke.FindNextFile(FindHandle, out FindData)); PInvoke.FindClose(FindHandle); return(false); }
public unsafe void LockNLoad(byte[][] cBufs, byte[][] xBufs, byte[][] oLaps, ISO_PKT_INFO[][] pktsInfo) { int j = 0; int nLocalCount = j; GCHandle[] bufSingleTransfer = new GCHandle[QueueSz]; GCHandle[] bufDataAllocation = new GCHandle[QueueSz]; GCHandle[] bufPktsInfo = new GCHandle[QueueSz]; GCHandle[] handleOverlap = new GCHandle[QueueSz]; while (j < QueueSz) { // Allocate one set of buffers for the queue, Buffered IO method require user to allocate a buffer as a part of command buffer, // the BeginDataXfer does not allocated it. BeginDataXfer will copy the data from the main buffer to the allocated while initializing the commands. cBufs[j] = new byte[CyConst.SINGLE_XFER_LEN]; xBufs[j] = new byte[BufSz]; //initialize the buffer with initial value 0xA5 for (int iIndex = 0; iIndex < BufSz; iIndex++) { xBufs[j][iIndex] = 0; } int sz = Math.Max(CyConst.OverlapSignalAllocSize, sizeof(OVERLAPPED)); oLaps[j] = new byte[sz]; pktsInfo[j] = new ISO_PKT_INFO[PPX]; /*///////////////////////////////////////////////////////////////////////////// * * fixed keyword is getting thrown own by the compiler because the temporary variables * tL0, tc0 and tb0 aren't used. And for jagged C# array there is no way, we can use this * temporary variable. * * Solution for Variable Pinning: * Its expected that application pin memory before passing the variable address to the * library and subsequently to the windows driver. * * Cypress Windows Driver is using this very same memory location for data reception or * data delivery to the device. * And, hence .Net Garbage collector isn't expected to move the memory location. And, * Pinning the memory location is essential. And, not through FIXED keyword, because of * non-usability of temporary variable. * * /////////////////////////////////////////////////////////////////////////////*/ //fixed (byte* tL0 = oLaps[j], tc0 = cBufs[j], tb0 = xBufs[j]) // Pin the buffers in memory ////////////////////////////////////////////////////////////////////////////////////////////// bufSingleTransfer[j] = GCHandle.Alloc(cBufs[j], GCHandleType.Pinned); bufDataAllocation[j] = GCHandle.Alloc(xBufs[j], GCHandleType.Pinned); bufPktsInfo[j] = GCHandle.Alloc(pktsInfo[j], GCHandleType.Pinned); handleOverlap[j] = GCHandle.Alloc(oLaps[j], GCHandleType.Pinned); // oLaps "fixed" keyword variable is in use. So, we are good. ///////////////////////////////////////////////////////////////////////////////////////////// unsafe { //fixed (byte* tL0 = oLaps[j]) { CyUSB.OVERLAPPED ovLapStatus = new CyUSB.OVERLAPPED(); ovLapStatus = (CyUSB.OVERLAPPED)Marshal.PtrToStructure(handleOverlap[j].AddrOfPinnedObject(), typeof(CyUSB.OVERLAPPED)); ovLapStatus.hEvent = (IntPtr)PInvoke.CreateEvent(0, 0, 0, 0); Marshal.StructureToPtr(ovLapStatus, handleOverlap[j].AddrOfPinnedObject(), true); // Pre-load the queue with a request int len = BufSz; if (BulkInEndPoint.BeginDataXfer(ref cBufs[j], ref xBufs[j], ref len, ref oLaps[j]) == false) { Failures++; } } j++; } } XferData(cBufs, xBufs, oLaps, pktsInfo, handleOverlap); // All loaded. Let's go! unsafe { for (nLocalCount = 0; nLocalCount < QueueSz; nLocalCount++) { CyUSB.OVERLAPPED ovLapStatus = new CyUSB.OVERLAPPED(); ovLapStatus = (CyUSB.OVERLAPPED)Marshal.PtrToStructure(handleOverlap[nLocalCount].AddrOfPinnedObject(), typeof(CyUSB.OVERLAPPED)); PInvoke.CloseHandle(ovLapStatus.hEvent); /*//////////////////////////////////////////////////////////////////////////////////////////// * * Release the pinned allocation handles. * * ////////////////////////////////////////////////////////////////////////////////////////////*/ bufSingleTransfer[nLocalCount].Free(); bufDataAllocation[nLocalCount].Free(); bufPktsInfo[nLocalCount].Free(); handleOverlap[nLocalCount].Free(); cBufs[nLocalCount] = null; xBufs[nLocalCount] = null; oLaps[nLocalCount] = null; } } GC.Collect(); }
private bool GetClusterInfo(FileInfo Info, ref SafeFileHandle Handle) { Info.Fragments.Clear(); string FullName = GetDBDir(Info.DirIndice) + Info.Name; PInvoke.BY_HANDLE_FILE_INFORMATION FileInfo; if ((Handle == null) || Handle.IsClosed || Handle.IsInvalid) { Handle = PInvoke.CreateFile( FullName, PInvoke.GENERIC_READ, PInvoke.FILE_SHARE_READ | PInvoke.FILE_SHARE_WRITE, IntPtr.Zero, PInvoke.OPEN_EXISTING, (Info.Attributes.Directory) ? PInvoke.FILE_FLAG_BACKUP_SEMANTICS : 0, IntPtr.Zero ); } if (Handle.IsInvalid || Handle.IsClosed) { Debug.WriteLine("Error #{0} occurred trying to open file '{1}'", Marshal.GetLastWin32Error(), FullName); Info.Attributes.AccessDenied = true; return(false); } var Result = PInvoke.GetFileInformationByHandle(Handle, out FileInfo); if (!Result) { Info.Attributes.AccessDenied = true; Debug.WriteLine("GetFileInformationByHandle ('{0}') failed\n", FullName); Handle.Close(); return(false); } // Get cluster allocation information PInvoke.LARGE_INTEGER StartingVCN = new PInvoke.LARGE_INTEGER(); IntPtr pDest = IntPtr.Zero; uint BytesReturned = 0; // Grab info one extent at a time, until it's done grabbing all the extent data // Yeah, well it doesn't give us a way to ask L"how many extents?" that I know of ... // btw, the Extents variable tends to only reflect memory usage, so when we have // all the extents we look at the structure Win32 gives us for the REAL count! uint Extents = 10; const uint RETRIEVAL_POINTERS_BUFFER_SIZE = 28; StartingVCN.QuadPart = 0; GCHandle handle = GCHandle.Alloc(StartingVCN, GCHandleType.Pinned); IntPtr StartingVCNPtr = handle.AddrOfPinnedObject(); do { Extents *= 2; var RetSize = RETRIEVAL_POINTERS_BUFFER_SIZE + (uint)((Extents - 1) * Marshal.SizeOf(typeof(PInvoke.LARGE_INTEGER)) * 2); pDest = pDest != IntPtr.Zero ? Marshal.ReAllocHGlobal(pDest, (IntPtr)RetSize) : Marshal.AllocHGlobal((int)RetSize); Result = PInvoke.DeviceIoControl ( Handle, PInvoke.FSConstants.FSCTL_GET_RETRIEVAL_POINTERS, StartingVCNPtr, (uint)Marshal.SizeOf(typeof(PInvoke.LARGE_INTEGER)), pDest, RetSize, ref BytesReturned, IntPtr.Zero ); if (!Result) { if (Marshal.GetLastWin32Error() != PInvoke.ERROR_MORE_DATA) { Debug.WriteLine("Error #{0} occurred trying to get retrieval pointers for file '{1}", Marshal.GetLastWin32Error(), FullName); Info.Clusters = 0; Info.Attributes.AccessDenied = true; Info.Attributes.Process = false; Info.Fragments.Clear(); Handle.Close(); Marshal.FreeHGlobal(pDest); return(false); } Extents++; } } while (!Result); var Retrieval = new PInvoke.RETRIEVAL_POINTERS_BUFFER(pDest); // Readjust extents, as it only reflects how much memory was allocated and may not // be accurate Extents = (uint)Retrieval.ExtentCount; // Ok, we have the info. Now translate it. hrmrmr Info.Fragments.Clear(); for (int i = 0; i < Extents; i++) { Extent Add; Add.StartLCN = Retrieval.Extents[i].Lcn.QuadPart; if (i != 0) { Add.Length = Retrieval.Extents[i].NextVcn.QuadPart - Retrieval.Extents[i - 1].NextVcn.QuadPart; } else { Add.Length = Retrieval.Extents[i].NextVcn.QuadPart - Retrieval.StartingVcn.QuadPart; } Info.Fragments.Add(Add); } Marshal.FreeHGlobal(pDest); return(true); }
private static ImageData LoadThumbnail(string path, DateTime dtLastWriteTime, out Size sizeRaw, out Size sizeActual, out string toolTipText, out bool fCached) { sizeRaw = sizeActual = Size.Empty; toolTipText = null; fCached = false; IntPtr zero = IntPtr.Zero; QTTabBarLib.Interop.IShellItem ppsi = null; ISharedBitmap ppvThumb = null; LocalThumbnailCache o = null; try { zero = PInvoke.ILCreateFromPath(path); if ((zero != IntPtr.Zero) && (PInvoke.SHCreateShellItem(IntPtr.Zero, null, zero, out ppsi) == 0)) { o = new LocalThumbnailCache(); IThumbnailCache cache2 = (IThumbnailCache)o; uint flags = 0; uint pOutFlags = 0; WTS_THUMBNAILID pThumbnailID = new WTS_THUMBNAILID(); uint cxyRequestedThumbSize = (uint)Math.Min(0x400, Math.Min(QTUtility.PreviewMaxWidth, QTUtility.PreviewMaxHeight)); if (cache2.GetThumbnail(ppsi, cxyRequestedThumbSize, flags, out ppvThumb, ref pOutFlags, ref pThumbnailID) == 0) { IntPtr ptr2; if ((pOutFlags & 2) == 2) { fCached = true; } if (ppvThumb.Detach(out ptr2) == 0) { Bitmap bmp = Image.FromHbitmap(ptr2); Size size = bmp.Size; sizeRaw = sizeActual = size; ImageData data = new ImageData(bmp, null, path, dtLastWriteTime, size, size); data.Thumbnail = true; try { toolTipText = data.TooltipText = ShellMethods.GetShellInfoTipText(zero, false); } catch { } return(data); } } } } catch (Exception exception) { QTUtility2.MakeErrorLog(exception, null); } finally { if (zero != IntPtr.Zero) { PInvoke.CoTaskMemFree(zero); } if (ppsi != null) { Marshal.ReleaseComObject(ppsi); } if (ppvThumb != null) { Marshal.ReleaseComObject(ppvThumb); } if (o != null) { Marshal.ReleaseComObject(o); } } return(null); }
/// <summary> /// Move file to new LCN /// </summary> /// <remarks>we have to move each fragment of the file, as per the Win32 API</remarks> /// <param name="FileIndice">File index</param> /// <param name="NewLCN">LCN</param> /// <returns>True if file was moved</returns> public bool MoveFileDumb(int FileIndice, ulong NewLCN) { bool ReturnVal; PInvoke.MoveFileData MoveData = new PInvoke.MoveFileData(); // NewLCN can't be less than 0 if (NewLCN == 0) { return(false); } // Set up variables var Info = GetDBFile((uint)FileIndice); var FullName = GetDBDir(Info.DirIndice); FullName += Info.Name; var CurrentLCN = NewLCN; ulong CurrentVCN = 0; /* * if (Info.Attributes.Directory == 1) * { * // * } */ // Open file var FileHandle = PInvoke.CreateFile ( FullName, PInvoke.GENERIC_READ, PInvoke.FILE_SHARE_READ, IntPtr.Zero, PInvoke.OPEN_EXISTING, (Info.Attributes.Directory) ? PInvoke.FILE_FLAG_BACKUP_SEMANTICS : 0, IntPtr.Zero ); if (FileHandle.IsClosed || FileHandle.IsInvalid) { Debug.WriteLine("Error #{0} occurred trying to get file handle for '{1}'", Marshal.GetLastWin32Error(), FullName); ReturnVal = false; } else { ReturnVal = true; // innocent until proven guilty ... try { for (int i = 0; i < Info.Fragments.Count; i++) { uint BytesReturned = 0; //wprintf (L"%3u", i); MoveData.ClusterCount = (uint)Info.Fragments[i].Length; MoveData.StartingLCN.QuadPart = CurrentLCN; MoveData.StartingVCN.QuadPart = CurrentVCN; MoveData.hFile = FileHandle.DangerousGetHandle(); GCHandle handle = GCHandle.Alloc(MoveData, GCHandleType.Pinned); IntPtr pInput = handle.AddrOfPinnedObject(); uint bufSize = (uint)Marshal.SizeOf(MoveData); /* * wprintf (L"\n"); * wprintf (L"StartLCN: %I64u\n", MoveData.StartingLcn.QuadPart); * wprintf (L"StartVCN: %I64u\n", MoveData.StartingVcn.QuadPart); * wprintf (L"Clusters: %u (%I64u-%I64u --> %I64u-%I64u)\n", MoveData.ClusterCount, * Info.Fragments[i].StartLCN, * Info.Fragments[i].StartLCN + MoveData.ClusterCount, * MoveData.StartingLcn.QuadPart, * MoveData.StartingLcn.QuadPart + MoveData.ClusterCount - 1); * wprintf (L"\n"); */ var Result = PInvoke.DeviceIoControl ( Handle, PInvoke.FSConstants.FSCTL_MOVE_FILE, pInput, bufSize, IntPtr.Zero, 0, ref BytesReturned, IntPtr.Zero ); //wprintf (L"\b\b\b"); if (!Result) { Debug.WriteLine("Error #{0} occurred trying to move file '{1}'", Marshal.GetLastWin32Error(), FullName); ReturnVal = false; break; // yeah, bite me } // Ok good. Now update our drive bitmap and file infos. ulong j; for (j = 0; j < Info.Fragments[i].Length; j++) { SetCluster(Info.Fragments[i].StartLCN + j, false); SetCluster(CurrentLCN + j, true); //BitmapDetail[Info.Fragments[i].StartLCN + j].Allocated = false; //BitmapDetail[CurrentLCN + j].Allocated = true; } CurrentLCN += Info.Fragments[i].Length; CurrentVCN += Info.Fragments[i].Length; } } catch { // ignored } finally { // Update file info either way FileInfo fileInfo = Files[FileIndice]; GetClusterInfo(fileInfo, ref FileHandle); FileHandle.Close(); } } return(ReturnVal); }
public Address(IntPtr pidl, string path) { this.ITEMIDLIST = PInvoke.GetIDListData(pidl); this.Path = path; }
/// <summary>Shows the taskbar.</summary> public static void Show() { const int SW_SHOW = 1; PInvoke.ShowWindow(TaskbarWindowHandle, SW_SHOW); }
protected override void WndProc(ref Message m) { if (VisualStyleRenderer.IsSupported) { switch (m.Msg) { case WM.MOUSEMOVE: { if (fTrackMouseEvent) { fTrackMouseEvent = false; PInvoke.TrackMouseEvent(ref TME); } bool flag = (((int)m.WParam) & 1) == 1; if ((((int)((long)m.LParam)) & 0xffff) < 0x13) { stateDown = flag ? 2 : 1; stateUP = 0; } else { stateDown = 0; stateUP = flag ? 2 : 1; } PInvoke.InvalidateRect(m.HWnd, IntPtr.Zero, false); break; } case WM.LBUTTONDOWN: if ((((int)((long)m.LParam)) & 0xffff) >= 0x13) { stateUP = 2; break; } stateDown = 2; break; case WM.LBUTTONUP: if ((((int)((long)m.LParam)) & 0xffff) >= 0x13) { stateUP = 1; break; } stateDown = 1; break; case WM.MOUSELEAVE: stateDown = stateUP = 0; fTrackMouseEvent = true; PInvoke.InvalidateRect(m.HWnd, IntPtr.Zero, false); break; case WM.PAINT: { if (rendererDown_Normal == null) { InitializeRenderer(); } IntPtr dC = PInvoke.GetDC(m.HWnd); if (!(dC != IntPtr.Zero)) { break; } using (Graphics graphics = Graphics.FromHdc(dC)) { VisualStyleRenderer renderer; VisualStyleRenderer renderer2; if (stateDown == 0) { renderer = rendererDown_Normal; } else if (stateDown == 1) { renderer = rendererDown_Hot; } else { renderer = rendererDown_Pressed; } if (stateUP == 0) { renderer2 = rendererUp_Normal; } else if (stateUP == 1) { renderer2 = rendererUp_Hot; } else { renderer2 = rendererUp_Pressed; } renderer.DrawBackground(graphics, rctDw); renderer2.DrawBackground(graphics, rctUp); } PInvoke.ReleaseDC(m.HWnd, dC); PInvoke.ValidateRect(m.HWnd, IntPtr.Zero); m.Result = IntPtr.Zero; return; } } } base.WndProc(ref m); }
private static bool RefreshBoundsAndPosition() { //! PInvoke.SHAppBarMessage returns IntPtr.Zero **if it fails** return(PInvoke.SHAppBarMessage(AppBarMessage.GetTaskbarPos, ref kAppBarData) != IntPtr.Zero); }
/// <summary> /// Returns the error message for the given status code /// </summary> /// <param name="statusCode">Status code to resolve</param> /// <returns></returns> private string GetMessageForStatusCode(ws2811_return_t statusCode) { var strPointer = PInvoke.ws2811_get_return_t_str((int)statusCode); return(Marshal.PtrToStringAuto(strPointer)); }
/// <summary>Hides the taskbar.</summary> public static void Hide() { const int SW_HIDE = 0; PInvoke.ShowWindow(TaskbarWindowHandle, SW_HIDE); }
protected virtual bool ListViewController_MessageCaptured(ref Message msg) { if (msg.Msg == WM_AFTERPAINT) { RefreshSubDirTip(true); return(true); } else if (msg.Msg == WM_REGISTERDRAGDROP) { IntPtr ptr = Marshal.ReadIntPtr(msg.WParam); if (dropTargetPassthrough != null) { // If this is the RegisterDragDrop call from the constructor, // don't mess it up! if (dropTargetPassthrough.Pointer == ptr) { return(true); } dropTargetPassthrough.Dispose(); } dropTargetPassthrough = TryMakeDTPassthrough(ptr); if (dropTargetPassthrough != null) { Marshal.WriteIntPtr(msg.WParam, dropTargetPassthrough.Pointer); } return(true); } switch (msg.Msg) { case WM.DESTROY: HideThumbnailTooltip(7); HideSubDirTip(7); ListViewController.DefWndProc(ref msg); OnListViewDestroyed(); return(true); case WM.PAINT: // It's very dangerous to do automation-related things // during WM_PAINT. So, use PostMessage to do it later. PInvoke.PostMessage(ListViewController.Handle, WM_AFTERPAINT, IntPtr.Zero, IntPtr.Zero); break; case WM.MOUSEMOVE: ResetTrackMouseEvent(); break; case WM.LBUTTONDBLCLK: if (DoubleClick != null) { return(DoubleClick(QTUtility2.PointFromLPARAM(msg.LParam))); } break; case WM.MBUTTONUP: if (MiddleClick != null) { MiddleClick(QTUtility2.PointFromLPARAM(msg.LParam)); } break; case WM.MOUSEWHEEL: { IntPtr handle = PInvoke.WindowFromPoint(QTUtility2.PointFromLPARAM(msg.LParam)); if (handle != IntPtr.Zero && handle != msg.HWnd) { Control control = Control.FromHandle(handle); if (control != null) { DropDownMenuReorderable reorderable = control as DropDownMenuReorderable; if ((reorderable != null) && reorderable.CanScroll) { PInvoke.SendMessage(handle, WM.MOUSEWHEEL, msg.WParam, msg.LParam); } } } break; } case WM.MOUSELEAVE: fTrackMouseEvent = true; HideThumbnailTooltip(4); if (((subDirTip != null) && !subDirTip.MouseIsOnThis()) && !subDirTip.MenuIsShowing) { HideSubDirTip(5); } break; } return(false); }
public static int GetSoundLength(string fileName) { int length; if (fileName.StartsWith("http://localhost:59125/process?")) { string timeURL = fileName.Replace("OUTPUT_TYPE=AUDIO", "OUTPUT_TYPE=REALISED_DURATIONS"); List <string> realised_durations = new List <string>(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(timeURL); // Set some reasonable limits on resources used by this request request.MaximumAutomaticRedirections = 4; request.MaximumResponseHeadersLength = 4; // Set credentials to use for this request. request.Credentials = CredentialCache.DefaultCredentials; HttpWebResponse response = null; try { response = (HttpWebResponse)request.GetResponse(); } catch { Log.Error("Unable to use MaryTTS voice synthesiser."); if (File.Exists(Settings.Default.MaryTTSLocation)) { Log.Error("Trying to restart MaryTTS server."); Process proc = new Process { StartInfo = new ProcessStartInfo { UseShellExecute = true, WindowStyle = ProcessWindowStyle.Minimized, // cannot close it if set to hidden CreateNoWindow = true, FileName = Settings.Default.MaryTTSLocation } }; try { proc.Start(); } catch { Log.ErrorFormat("Failed to restart MaryTTS server. Disabling MaryTTS and using System Voice '{0}' instead.", Settings.Default.SpeechVoice); Settings.Default.MaryTTSEnabled = false; } if (proc.StartTime <= DateTime.Now && !proc.HasExited) { Log.InfoFormat("Restarted MaryTTS server at {0}.", proc.StartTime); proc.CloseOnApplicationExit(Log, "MaryTTS"); } else { var errorMsg = string.Format( "Failed to started MaryTTS (server not running). Disabling MaryTTS and using System Voice '{0}' instead.", Settings.Default.SpeechVoice); if (proc.HasExited) { errorMsg = string.Format( "Failed to started MaryTTS (server was closed). Disabling MaryTTS and using System Voice '{0}' instead.", Settings.Default.SpeechVoice); } Log.Error(errorMsg); Settings.Default.MaryTTSEnabled = false; } } else { Log.ErrorFormat("Failed to restart MaryTTS server. Disabling MaryTTS and using System Voice '{0}' instead.", Settings.Default.SpeechVoice); Settings.Default.MaryTTSEnabled = false; } } if (response != null) { // Get the stream associated with the response. Stream receiveStream = response.GetResponseStream(); // Pipes the stream to a higher level stream reader with the required encoding format. StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8); string responseText = readStream.ReadToEnd(); realised_durations = responseText.Split('\n').ToList(); // retrieve the time of the last syllable length = (int)(1000 * Convert.ToSingle(realised_durations.ElementAt(realised_durations.Count() - 2).Split(' ').ToList().ElementAt(0))); return(length); } } else { StringBuilder lengthBuf = new StringBuilder(32); PInvoke.mciSendString(string.Format("open \"{0}\" type waveaudio alias wave", fileName), null, 0, IntPtr.Zero); PInvoke.mciSendString("status wave length", lengthBuf, lengthBuf.Capacity, IntPtr.Zero); PInvoke.mciSendString("close wave", null, 0, IntPtr.Zero); int.TryParse(lengthBuf.ToString(), out length); return(length); } return(0); //This is an error condition }
public void GetTickCount_Nonzero() { uint result = PInvoke.GetTickCount(); Assert.NotEqual(0u, result); }
static void GetControlRect(IntPtr hWnd, IntPtr controlHWND, out PInvoke.RECT rect) { PInvoke.GetWindowRect(controlHWND, out rect); var pt = new PInvoke.POINT(rect.Left, rect.Top); PInvoke.ScreenToClient(hWnd, ref pt); rect.Right = rect.Right - rect.Left + pt.X; rect.Bottom = rect.Bottom - rect.Top + pt.Y; rect.Left = pt.X; rect.Top = pt.Y; }