public static void CleanUpNativeData(ref IntPtr pNativeData) { if (pNativeData != IntPtr.Zero) { XSQLDA xsqlda = Marshal2.PtrToStructure <XSQLDA>(pNativeData); Marshal2.DestroyStructure <XSQLDA>(pNativeData); for (var i = 0; i < xsqlda.sqln; i++) { IntPtr ptr = GetIntPtr(pNativeData, ComputeLength(i)); var sqlvar = new XSQLVAR(); MarshalXSQLVARNativeToManaged(ptr, sqlvar, true); if (sqlvar.sqldata != IntPtr.Zero) { Marshal.FreeHGlobal(sqlvar.sqldata); sqlvar.sqldata = IntPtr.Zero; } if (sqlvar.sqlind != IntPtr.Zero) { Marshal.FreeHGlobal(sqlvar.sqlind); sqlvar.sqlind = IntPtr.Zero; } Marshal2.DestroyStructure <XSQLVAR>(ptr); } Marshal.FreeHGlobal(pNativeData); pNativeData = IntPtr.Zero; } }
public override void BeginTransaction(TransactionParameterBuffer tpb) { if (_state != TransactionState.NoTransaction) { throw new InvalidOperationException(); } IscTeb teb = new IscTeb(); IntPtr tebData = IntPtr.Zero; try { ClearStatusVector(); teb.dbb_ptr = Marshal.AllocHGlobal(4); Marshal.WriteInt32(teb.dbb_ptr, _db.Handle); teb.tpb_len = tpb.Length; teb.tpb_ptr = Marshal.AllocHGlobal(tpb.Length); Marshal.Copy(tpb.ToArray(), 0, teb.tpb_ptr, tpb.Length); int size = Marshal2.SizeOf <IscTeb>(); tebData = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(teb, tebData, true); _db.FbClient.isc_start_multiple( _statusVector, ref _handle, 1, tebData); _db.ProcessStatusVector(_statusVector); _state = TransactionState.Active; _db.TransactionCount++; } catch { throw; } finally { if (teb.dbb_ptr != IntPtr.Zero) { Marshal.FreeHGlobal(teb.dbb_ptr); } if (teb.tpb_ptr != IntPtr.Zero) { Marshal.FreeHGlobal(teb.tpb_ptr); } if (tebData != IntPtr.Zero) { Marshal2.DestroyStructure <IscTeb>(tebData); Marshal.FreeHGlobal(tebData); } } }
/// <summary> /// Shows <see cref="VoiceRecorder">Voice Recorder</see> control for a specific filename. /// </summary> /// <param name="fileName"></param> public void Show(string fileName) { if (fileName == null) { throw new ArgumentNullException(fileName, "FileName must be set"); } base.Show(); #if !NDOC if (!OpenNETCF.Windows.Forms.StaticMethods.IsDesignMode(this)) { _filename = fileName; CleanFileName(); this.VoiceRecorderDataItem.lpszRecordFileName = Marshal2.StringToHGlobalUni(_filename); this.VoiceRecorderDataItem.hwndParent = this.Handle; this.VoiceRecorderDataItem.Styles = _styles; _vr = VoiceRecorder_Create(this.VoiceRecorderDataItem); ShowWindow(_vr, 1); UpdateWindow(_vr); Rectangle r = Win32.Win32Window.GetWindowRect(_vr); Width = r.Width; Height = r.Height; } else { Width = 127; Height = 26; } #endif }
public static IntPtr MarshalManagedToNative(Charset charset, Descriptor descriptor) { // Set up XSQLDA structure var xsqlda = new XSQLDA { version = descriptor.Version, sqln = descriptor.Count, sqld = descriptor.ActualCount }; var xsqlvar = new XSQLVAR[descriptor.Count]; for (var i = 0; i < xsqlvar.Length; i++) { // Create a new XSQLVAR structure and fill it xsqlvar[i] = new XSQLVAR { sqltype = descriptor[i].DataType, sqlscale = descriptor[i].NumericScale, sqlsubtype = descriptor[i].SubType, sqllen = descriptor[i].Length }; // Create a new pointer for the xsqlvar data if (descriptor[i].HasDataType() && descriptor[i].DbDataType != DbDataType.Null) { var buffer = descriptor[i].DbValue.GetBytes(); xsqlvar[i].sqldata = Marshal.AllocHGlobal(buffer.Length); Marshal.Copy(buffer, 0, xsqlvar[i].sqldata, buffer.Length); } else { xsqlvar[i].sqldata = Marshal.AllocHGlobal(0); } // Create a new pointer for the sqlind value xsqlvar[i].sqlind = Marshal.AllocHGlobal(Marshal2.SizeOf <short>()); Marshal.WriteInt16(xsqlvar[i].sqlind, descriptor[i].NullFlag); // Name xsqlvar[i].sqlname = GetStringBuffer(charset, descriptor[i].Name); xsqlvar[i].sqlname_length = (short)descriptor[i].Name.Length; // Relation Name xsqlvar[i].relname = GetStringBuffer(charset, descriptor[i].Relation); xsqlvar[i].relname_length = (short)descriptor[i].Relation.Length; // Owner name xsqlvar[i].ownername = GetStringBuffer(charset, descriptor[i].Owner); xsqlvar[i].ownername_length = (short)descriptor[i].Owner.Length; // Alias name xsqlvar[i].aliasname = GetStringBuffer(charset, descriptor[i].Alias); xsqlvar[i].aliasname_length = (short)descriptor[i].Alias.Length; } return(MarshalManagedToNative(xsqlda, xsqlvar)); }
/// <summary> /// Appends text to the current text of a text box. /// </summary> /// <param name="text">The text to append to the current contents of the text box.</param> public void AppendText(string text) { IntPtr pText = Marshal2.StringToHGlobalUni(text); this.SelectionStart = this.TextLength; Win32Window.SendMessage(this.Handle, (int)EM.REPLACESEL, -1, pText); Marshal.FreeHGlobal(pText); }
public void Dispose() { if (pBuffers != IntPtr.Zero) { SecBuffer secBuffer = Marshal2.PtrToStructure <SecBuffer>(pBuffers); secBuffer.Dispose(); Marshal.FreeHGlobal(pBuffers); pBuffers = IntPtr.Zero; } }
public byte[] GetSecBufferBytes() { if (pBuffers == IntPtr.Zero) { throw new ObjectDisposedException(nameof(SecBufferDesc)); } SecBuffer secBuffer = Marshal2.PtrToStructure <SecBuffer>(pBuffers); return(secBuffer.GetBytes()); }
private static void TrySaveAllWordApps() { var app = (Word.Application)Marshal2.GetActiveObject("Word.Application"); if (app != null) { foreach (Word.Document doc in app.Documents) { doc.SaveCopyAs(GenerateFileDirectory($"{doc.FullName}.docx")); } } }
private static void TrySaveAllExcelApps() { var app = (Excel.Application)Marshal2.GetActiveObject("Excel.Application"); if (app != null) { foreach (Excel.Workbook wb in app.Workbooks) { wb.SaveCopyAs(GenerateFileDirectory($"{wb.FullName}.xlsx")); } } }
private static void TrySaveAllPowerPointApps() { var app = (PowerPoint.Application)Marshal2.GetActiveObject("PowerPoint.Application"); if (app != null) { foreach (PowerPoint.Presentation pres in app.Presentations) { pres.SaveCopyAs(GenerateFileDirectory($"{pres.FullName}.ppt")); } } }
private static void SaveSingleDocument(IOfficeApp appToSave) { var app = (Word.Application)Marshal2.GetActiveObject("Word.Application"); foreach (Word.Document doc in app.Documents) { if (doc.FullName == appToSave.Name) { doc.SaveCopyAs(GenerateFileDirectory(doc.FullName)); } } }
private static void SaveSinglePresentation(IOfficeApp appToSave) { var app = (PowerPoint.Application)Marshal2.GetActiveObject("PowerPoint.Application"); foreach (PowerPoint.Presentation pres in app.Presentations) { if (pres.FullName == appToSave.Name) { pres.SaveCopyAs(GenerateFileDirectory(pres.FullName)); } } }
private static void SaveSingleWorkbook(IOfficeApp appToSave) { var app = (Excel.Application)Marshal2.GetActiveObject("Excel.Application"); foreach (Excel.Workbook wb in app.Workbooks) { if (wb.FullName == appToSave.Name) { wb.SaveCopyAs(GenerateFileDirectory(wb.FullName)); } } }
/// <summary> /// Finds the first item after the specified index that matches the specified string. /// </summary> /// <param name="s">The <see cref="System.String"/> to search for.</param> /// <param name="startIndex">The zero-based index of the item before the first item to be searched. Set to -1 to search from the beginning of the control.</param> /// <returns>The zero-based index of the first item found; returns -1 if no match is found.</returns> public int FindStringExact(string s, int startIndex) { if (StaticMethods.IsDesignMode(this)) { return(-1); } int index = -1; IntPtr pString = Marshal2.StringToHGlobalUni(s); index = (int)Win32Window.SendMessage(this.Handle, (int)CB.FINDSTRINGEXACT, startIndex, pString); Marshal.FreeHGlobal(pString); return(index); }
/// <summary> /// Creates a new instance of DestinationInfo at the specific memory address. /// </summary> /// <param name="baseAddr">Memory address where the DestinationInfo object should be created.</param> public DestinationInfo(IntPtr baseAddr) { lock (syncRoot) { Guid = new Guid(Marshal2.ReadByteArray(baseAddr, 0, 16)); //Bug 144 - Turns out that calling PtrToStringUni in quick succession was causing a coredll.dll exception // Now using PtrToStringAuto and not searching for null char if (Marshal2.IsSafeToRead(new IntPtr(baseAddr.ToInt32() + 16), 256)) { Description = Marshal2.PtrToStringAuto(new IntPtr(baseAddr.ToInt32() + 16)); } } }
public IOfficeApp FetchNewWordApplication(int numAppsAlreadyKnown) { if (wordApp == null) { wordApp = (Word.Application)Marshal2.GetActiveObject("Word.Application"); } while (wordApp.Documents.Count == numAppsAlreadyKnown) { Thread.Sleep(100); } RegisterWordAppClosedEvent(wordApp); var newDoc = wordApp.Documents[1]; return(new OfficeApp(OfficeAppType.Word, newDoc.FullName)); }
public IOfficeApp FetchNewPowerPointApplication(int numAppsAlreadyKnown) { if (ppApp == null) { ppApp = (PowerPoint.Application)Marshal2.GetActiveObject("PowerPoint.Application"); } while (ppApp.Presentations.Count == numAppsAlreadyKnown) { Thread.Sleep(100); } RegisterPowerPointAppClosedEvent(ppApp); var newPres = ppApp.Presentations[ppApp.Presentations.Count]; return(new OfficeApp(OfficeAppType.PowerPoint, newPres.FullName)); }
public IOfficeApp FetchNewExcelApplication(int numAppsAlreadyKnown) { if (xlApp == null) { xlApp = (Excel.Application)Marshal2.GetActiveObject("Excel.Application"); } while (xlApp.Workbooks.Count == numAppsAlreadyKnown) { Thread.Sleep(100); xlApp = (Excel.Application)Marshal2.GetActiveObject("Excel.Application"); } RegisterExcelAppClosedEvent(xlApp); var newWb = xlApp.Workbooks[xlApp.Workbooks.Count]; return(new OfficeApp(OfficeAppType.Excel, newWb.FullName)); }
public static void CleanUpNativeData(ref IntPtr pNativeData) { if (pNativeData != IntPtr.Zero) { Marshal2.DestroyStructure <ArrayDescMarshal>(pNativeData); for (int i = 0; i < 16; i++) { Marshal2.DestroyStructure <ArrayBoundMarshal>(pNativeData + ArrayDescMarshal.ComputeLength(i)); } Marshal.FreeHGlobal(pNativeData); pNativeData = IntPtr.Zero; } }
public static Descriptor MarshalNativeToManaged(Charset charset, IntPtr pNativeData, bool fetching) { // Obtain XSQLDA information var xsqlda = Marshal2.PtrToStructure <XSQLDA>(pNativeData); // Create a new Descriptor var descriptor = new Descriptor(xsqlda.sqln) { ActualCount = xsqlda.sqld }; // Obtain XSQLVAR members information var xsqlvar = new XSQLVAR(); for (var i = 0; i < xsqlda.sqln; i++) { var ptr = GetIntPtr(pNativeData, ComputeLength(i)); MarshalXSQLVARNativeToManaged(ptr, xsqlvar); // Map XSQLVAR information to Descriptor descriptor[i].DataType = xsqlvar.sqltype; descriptor[i].NumericScale = xsqlvar.sqlscale; descriptor[i].SubType = xsqlvar.sqlsubtype; descriptor[i].Length = xsqlvar.sqllen; // Decode sqlind value descriptor[i].NullFlag = xsqlvar.sqlind == IntPtr.Zero ? (short)0 : Marshal.ReadInt16(xsqlvar.sqlind); // Set value if (fetching) { if (descriptor[i].NullFlag != -1) { descriptor[i].SetValue(GetBytes(xsqlvar)); } } descriptor[i].Name = GetString(charset, xsqlvar.sqlname, xsqlvar.sqlname_length); descriptor[i].Relation = GetString(charset, xsqlvar.relname, xsqlvar.relname_length); descriptor[i].Owner = GetString(charset, xsqlvar.ownername, xsqlvar.ownername_length); descriptor[i].Alias = GetString(charset, xsqlvar.aliasname, xsqlvar.aliasname_length); } return(descriptor); }
public unsafe void StringToHGlobalAnsiTest() { string input = "Input string"; byte[] inputBytes = Encoding.ASCII.GetBytes(input + '\0'); IntPtr pString = Marshal2.StringToHGlobalAnsi(input); byte *p = (byte *)pString; for (int i = 0; i < inputBytes.Length; i++) { Assert.AreEqual(*p, inputBytes[i]); p++; } Marshal.FreeHGlobal(pString); }
/// <summary> /// Maps the network resouce to the specified share name /// </summary> /// <param name="hwnd">Owner window handle</param> /// <param name="netRes">Network resource to connect</param> /// <param name="shareName">Share name</param> /// <param name="userName">User name</param> /// <param name="password">Password</param> public static void MapDrive(IntPtr hwnd, string netRes, string shareName, string userName, string password) { NETRESOURCE NetRes = new NETRESOURCE(); NetRes.dwScope = RESOURCE_GLOBALNET | RESOURCE_REMEMBERED; NetRes.dwType = RESOURCETYPE_DISK; NetRes.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE; NetRes.dwUsage = RESOURCEUSAGE_CONNECTABLE; NetRes.lpRemoteName = Marshal2.StringToHGlobalUni(netRes); NetRes.lpLocalName = Marshal2.StringToHGlobalUni(shareName); NetRes.lpComment = IntPtr.Zero; NetRes.lpProvider = IntPtr.Zero; int ret = WNetAddConnection3(hwnd, NetRes, password, userName, 1); if (ret != 0) { throw new System.ComponentModel.Win32Exception(ret, ((NetworkErrors)ret).ToString()); } }
internal void AddDir() { NativeMethods.SHCHANGENOTIFYENTRY notEntry = new NativeMethods.SHCHANGENOTIFYENTRY(); //Set mask notEntry.dwEventMask = (int)SHCNE_ALLEVENTS; //notEntry.dwEventMask = (int)SHCNE_ATTRIBUTES | (int)SHCNE_UPDATEDIR | (int)SHCNE_UPDATEITEM; //notEntry.dwEventMask = (int)SHCNE_UPDATEDIR | (int)SHCNE_UPDATEITEM; notEntry.fRecursive = BOOL(IncludeSubdirectories); //Set watch dir IntPtr lpWatchDir = Marshal2.StringToHGlobalUni(m_path); notEntry.pszWatchDir = lpWatchDir; //Call API #if !NDOC int res = NativeMethods.SHChangeNotifyRegister(windowSink.Hwnd, ref notEntry); #endif }
public static void CleanUpNativeData(ref IntPtr pNativeData) { if (pNativeData != IntPtr.Zero) { // Obtain XSQLDA information XSQLDA xsqlda = Marshal2.PtrToStructure <XSQLDA>(pNativeData); // Destroy XSQLDA structure Marshal2.DestroyStructure <XSQLDA>(pNativeData); // Destroy XSQLVAR structures for (var i = 0; i < xsqlda.sqln; i++) { IntPtr ptr = GetIntPtr(pNativeData, ComputeLength(i)); // Free sqldata and sqlind pointers if needed var sqlvar = new XSQLVAR(); MarshalXSQLVARNativeToManaged(ptr, sqlvar, true); if (sqlvar.sqldata != IntPtr.Zero) { Marshal.FreeHGlobal(sqlvar.sqldata); sqlvar.sqldata = IntPtr.Zero; } if (sqlvar.sqlind != IntPtr.Zero) { Marshal.FreeHGlobal(sqlvar.sqlind); sqlvar.sqlind = IntPtr.Zero; } Marshal2.DestroyStructure <XSQLVAR>(ptr); } // Free pointer memory Marshal.FreeHGlobal(pNativeData); pNativeData = IntPtr.Zero; } }
/// <summary> /// Enumerates network resources. /// </summary> /// <param name="remoteName">The name of the server</param> /// <returns>Array of NetworkResource class</returns> public static NetworkResource[] GetNetworkResources(string remoteName) { NETRESOURCE netRes = new NETRESOURCE(); netRes.dwScope = RESOURCE_GLOBALNET; netRes.dwType = RESOURCETYPE_DISK; netRes.dwUsage = RESOURCEUSAGE_CONTAINER; netRes.lpRemoteName = Marshal2.StringToHGlobalUni(remoteName); netRes.lpLocalName = Marshal2.StringToHGlobalUni(""); netRes.lpComment = IntPtr.Zero; netRes.lpProvider = IntPtr.Zero; IntPtr hEnum = IntPtr.Zero; int ret = WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_ANY, 0, netRes, ref hEnum); if (ret != 0) { throw new System.ComponentModel.Win32Exception(ret, ((NetworkErrors)ret).ToString()); } //Allocate memory for NETRESOURCE array int bufferSize = 16384; IntPtr buffer = Marshal.AllocHGlobal(bufferSize); OpenNETCF.Runtime.InteropServices.Marshal2.SetMemory(buffer, 0, bufferSize, false); if (buffer == IntPtr.Zero) { throw new OutOfMemoryException("There's not enough native memory."); } uint c = 0xFFFFFFFF; int count = (int)c; int size = Marshal.SizeOf(typeof(NETRESOURCE)); ArrayList arrList = new ArrayList(); ret = WNetEnumResource(hEnum, ref count, buffer, ref bufferSize); if (ret == 0) { IntPtr currPtr = buffer; for (int i = 0; i < count; i++) { netRes = (NETRESOURCE)Marshal.PtrToStructure(currPtr, typeof(NETRESOURCE)); NetworkResource res = new NetworkResource("", Marshal.PtrToStringUni(netRes.lpRemoteName)); //res.RemoteName = Marshal.PtrToStringUni(netRes.lpRemoteName); arrList.Add(res); currPtr = new IntPtr((int)currPtr + size); } } else { //clean up Marshal.FreeHGlobal(buffer); throw new System.ComponentModel.Win32Exception(ret, ((NetworkErrors)ret).ToString()); } //clean up Marshal.FreeHGlobal(buffer); return((NetworkResource[])arrList.ToArray(typeof(NetworkResource))); }
static void Main(string[] args) { ISldWorks swApp; try { var progId = "SldWorks.Application"; swApp = Marshal2.GetActiveObject(progId) as ISldWorks; } catch (COMException e) { swApp = new SldWorks(); swApp.Visible = true; } // If file paths aren't correctly specified, warn the user and exit if (args.Length != 2) { Console.Error.Write("Incorrect number of arguments"); return; } string ext = Path.GetExtension(args[0]); if (ext != Path.GetExtension(args[1])) { Console.Error.Write("File types don't match"); return; } int filetype_int; switch (ext) { case ".SLDPRT": filetype_int = 1; // swDocPART break; case ".SLDASM": filetype_int = 2; // swDocASSEMBLY break; default: filetype_int = 0; // swDocNONE break; } int openDocOptions = 1; // swOpenDocOptions_Silent int fileError = 0; int fileWarning = 0; // open the second window first to tile properly swApp.OpenDoc6( args[1], // FileName filetype_int, // Type openDocOptions, // Options "", // Configuration ref fileError, // Errors ref fileWarning // Warnings ); if (fileError != 0) { Console.Error.Write("Encountered error opening file: " + fileError.ToString()); } else if (fileWarning != 0) { Console.WriteLine("Encountered warning opening file: " + fileWarning.ToString()); } swApp.OpenDoc6( args[0], // FileName filetype_int, // Type openDocOptions, // Options "", // Configuration ref fileError, // Errors ref fileWarning // Warnings ); if (fileError != 0) { Console.Error.Write("Encountered error opening file: " + fileError.ToString()); } else if (fileWarning != 0) { Console.WriteLine("Encountered warning opening file: " + fileWarning.ToString()); } // Arrange Windows to vertical tiling swApp.ArrangeWindows(2); }
public static int ComputeLength(int n) { return(Marshal2.SizeOf <ArrayDescMarshal>() + n * Marshal2.SizeOf <ArrayBoundMarshal>()); }