Search Results

Search found 505 results on 21 pages for 'intptr'.

Page 6/21 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • Click at specified client area

    - by VixinG
    Click doesn't work - I don't know why and can't find a solution :( ie. Click(150,215) should move mouse to the client area and click there. [DllImport("user32.dll")] private static extern bool ScreenToClient(IntPtr hWnd, ref Point lpPoint); [DllImport("user32", SetLastError = true)] private static extern int SetCursorPos(int x, int y); static void MouseMove(int x, int y) { Point p = new Point(x * -1, y * -1); ScreenToClient(hWnd, ref p); p = new Point(p.X * -1, p.Y * -1); SetCursorPos(p.X, p.Y); } static void Click(int x, int y) { MouseMove(x, y); SendMessage(hWnd, WM_LBUTTONDOWN, (IntPtr)0x1, new IntPtr(y * 0x10000 + x)); SendMessage(hWnd, WM_LBUTTONUP, (IntPtr)0x1, new IntPtr(y * 0x10000 + x)); } Edit: Of course I can use mouse_event for that, but I would like to see a solution for SendMessage()... [DllImport("user32.dll")] static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo); const int LEFTDOWN = 0x00000002; const int LEFTUP = 0x00000004; static void Click(int x, int y) { MouseMove(x, y); mouse_event((int)(LEFTDOWN), 0, 0, 0, 0); mouse_event((int)(LEFTUP), 0, 0, 0, 0); }

    Read the article

  • Is it possible to specify a function with both extern and override modifiers?

    - by Jeffrey Greenham
    I'm trying to override the behavior of an external function in user32.dll because I don't want a certain window to show up. What I'm trying to do is this: [DllImport("user32.dll")] public extern override IntPtr GetSystemMenu(IntPtr hMenu, bool bRevert) { return new IntPtr(); } but this won't work because I get the following errors: ... no suitable method found to override and ... cannot be extern and declare a body Is there any way to simulate what I'm trying to do?

    Read the article

  • IIS 7.5 Manager crashes when adding a custom error page

    - by dig412
    I'm running a local IIS 7.5 server in Win 7 Pro, and I'm trying to add a custom error page for 403 responses. When I click OK to add a custom error page for my site, IIS Manager just vanishes. The server is still running, and I can re-start IIS Manager, but the new page has not been saved. I've also tried adding it directly to web.config, but that just gives me The page cannot be displayed because an internal server error has occurred. Does anyone know why this might be happening? Edit: The event log implies that an invalid character in the path caused the crash, but It occured even when I copied & pasted a path from a valid entry. Application error log: IISMANAGER_CRASH IIS Manager terminated unexpectedly. Exception:System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. --- System.ArgumentException: Illegal characters in path. at System.IO.Path.CheckInvalidPathChars(String path) at System.IO.Path.IsPathRooted(String path) at Microsoft.Web.Management.Iis.CustomErrors.CustomErrorsForm.OnAccept() at Microsoft.Web.Management.Client.Win32.TaskForm.OnOKButtonClick(Object sender, EventArgs e) at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ButtonBase.WndProc(Message& m) at System.Windows.Forms.Button.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Form.ShowDialog(IWin32Window owner) at Microsoft.Web.Management.Host.UserInterface.ManagementUIService.ShowDialogInternal(Form form, IWin32Window parent) at Microsoft.Web.Management.Host.UserInterface.ManagementUIService.Microsoft.Web.Management.Client.Win32.IManagementUIService.ShowDialog(DialogForm form) at Microsoft.Web.Management.Client.Win32.ModulePage.ShowDialog(DialogForm form) at Microsoft.Web.Management.Iis.CustomErrors.CustomErrorsPage.AddCustomError() --- End of inner exception stack trace --- at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at Microsoft.Web.Management.Client.TaskList.InvokeMethod(String methodName, Object userData) at Microsoft.Web.Management.Host.UserInterface.Tasks.MethodTaskItemLine.InvokeMethod() at System.Windows.Forms.LinkLabel.OnMouseUp(MouseEventArgs e) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.Label.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at Microsoft.Web.Management.Host.Shell.ShellApplication.Execute(Boolean localDevelopmentMode, Boolean resetPreferences, Boolean resetPreferencesNoLaunch) Process:InetMgr

    Read the article

  • Problem Loading a DLL (4 replies)

    I'm having some issues now that I can't see what I'm doing wrong. I'm Pinvoking a non WindowsAPI DLL (I mean, not a dll provided on windows). Pinvoking LoadLibrary, I can get a IntPtr to any WindowsAPI DLL, but never I can get a pointer to my DLL. The code I'm using is very simple, like this one: [DllImport(&quot;kernel32.dll&quot;, SetLastError true)] public static extern IntPtr LoadLibrary(); static void ...

    Read the article

  • Problem Loading a DLL (4 replies)

    I'm having some issues now that I can't see what I'm doing wrong. I'm Pinvoking a non WindowsAPI DLL (I mean, not a dll provided on windows). Pinvoking LoadLibrary, I can get a IntPtr to any WindowsAPI DLL, but never I can get a pointer to my DLL. The code I'm using is very simple, like this one: [DllImport(&quot;kernel32.dll&quot;, SetLastError true)] public static extern IntPtr LoadLibrary(); static void ...

    Read the article

  • How to print PCL Directly to the printer? Vb.net VS 2010

    - by Justin
    Good day, I've been trying to upgrade an old Print Program that prints raw pcl directly to the printer. The print program takes a PCL Mask and a PCL Batch Spool File (just pcl with page turn commands, I think) merges them and sends them off to the printer. I'm able to send to the Printer a file stream of PCL but I get mixed results and i do not understand why printing is so difficult under .net. I mean yes there is the PrintDocument class, but to print PCL... Let's just say I'm ready to detach my printer from the network and burn it a live. Here is my class PrintDirect (rather a hybrid class) Imports System Imports System.Text Imports System.Runtime.InteropServices <StructLayout(LayoutKind.Sequential)> _ Public Structure DOCINFO <MarshalAs(UnmanagedType.LPWStr)> _ Public pDocName As String <MarshalAs(UnmanagedType.LPWStr)> _ Public pOutputFile As String <MarshalAs(UnmanagedType.LPWStr)> _ Public pDataType As String End Structure 'DOCINFO Public Class PrintDirect <DllImport("winspool.drv", CharSet:=CharSet.Unicode, ExactSpelling:=False, CallingConvention:=CallingConvention.StdCall)> _ Public Shared Function OpenPrinter(ByVal pPrinterName As String, ByRef phPrinter As IntPtr, ByVal pDefault As Integer) As Long End Function <DllImport("winspool.drv", CharSet:=CharSet.Unicode, ExactSpelling:=False, CallingConvention:=CallingConvention.StdCall)> _ Public Shared Function StartDocPrinter(ByVal hPrinter As IntPtr, ByVal Level As Integer, ByRef pDocInfo As DOCINFO) As Long End Function <DllImport("winspool.drv", CharSet:=CharSet.Unicode, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _ Public Shared Function StartPagePrinter(ByVal hPrinter As IntPtr) As Long End Function <DllImport("winspool.drv", CharSet:=CharSet.Ansi, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _ Public Shared Function WritePrinter(ByVal hPrinter As IntPtr, ByVal data As String, ByVal buf As Integer, ByRef pcWritten As Integer) As Long End Function <DllImport("winspool.drv", CharSet:=CharSet.Unicode, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _ Public Shared Function EndPagePrinter(ByVal hPrinter As IntPtr) As Long End Function <DllImport("winspool.drv", CharSet:=CharSet.Unicode, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _ Public Shared Function EndDocPrinter(ByVal hPrinter As IntPtr) As Long End Function <DllImport("winspool.drv", CharSet:=CharSet.Unicode, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _ Public Shared Function ClosePrinter(ByVal hPrinter As IntPtr) As Long End Function 'Helps uses to work with the printer Public Class PrintJob ''' <summary> ''' The address of the printer to print to. ''' </summary> ''' <remarks></remarks> Public PrinterName As String = "" Dim lhPrinter As New System.IntPtr() ''' <summary> ''' The object deriving from the Win32 API, Winspool.drv. ''' Use this object to overide the settings defined in the PrintJob Class. ''' </summary> ''' <remarks>Only use this when absolutly nessacary.</remarks> Public OverideDocInfo As New DOCINFO() ''' <summary> ''' The PCL Control Character or the ascii escape character. \x1b ''' </summary> ''' <remarks>ChrW(27)</remarks> Public Const PCL_Control_Character As Char = ChrW(27) ''' <summary> ''' Opens a connection to a printer, if false the connection could not be established. ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Function OpenPrint() As Boolean Dim rtn_val As Boolean = False PrintDirect.OpenPrinter(PrinterName, lhPrinter, 0) If Not lhPrinter = 0 Then rtn_val = True End If Return rtn_val End Function ''' <summary> ''' The name of the Print Document. ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public Property DocumentName As String Get Return OverideDocInfo.pDocName End Get Set(ByVal value As String) OverideDocInfo.pDocName = value End Set End Property ''' <summary> ''' The type of Data that will be sent to the printer. ''' </summary> ''' <value>Send the print data type, usually "RAW" or "LPR". To overide use the OverideDocInfo Object</value> ''' <returns>The DataType as it was provided, if it is not part of the enumeration it is set to "UNKNOWN".</returns> ''' <remarks></remarks> Public Property DocumentDataType As PrintDataType Get Select Case OverideDocInfo.pDataType.ToUpper Case "RAW" Return PrintDataType.RAW Case "LPR" Return PrintDataType.LPR Case Else Return PrintDataType.UNKOWN End Select End Get Set(ByVal value As PrintDataType) OverideDocInfo.pDataType = [Enum].GetName(GetType(PrintDataType), value) End Set End Property Public Property DocumentOutputFile As String Get Return OverideDocInfo.pOutputFile End Get Set(ByVal value As String) OverideDocInfo.pOutputFile = value End Set End Property Enum PrintDataType UNKOWN = 0 RAW = 1 LPR = 2 End Enum ''' <summary> ''' Initializes the printing matrix ''' </summary> ''' <param name="PrintLevel">I have no idea what the hack this is...</param> ''' <remarks></remarks> Public Sub OpenDocument(Optional ByVal PrintLevel As Integer = 1) PrintDirect.StartDocPrinter(lhPrinter, PrintLevel, OverideDocInfo) End Sub ''' <summary> ''' Starts the next page. ''' </summary> ''' <remarks></remarks> Public Sub StartPage() PrintDirect.StartPagePrinter(lhPrinter) End Sub ''' <summary> ''' Writes a string to the printer, can be used to write out a section of the document at a time. ''' </summary> ''' <param name="data">The String to Send out to the Printer.</param> ''' <returns>The pcWritten as an integer, 0 may mean the writter did not write out anything.</returns> ''' <remarks>Warning the buffer is automatically created by the lenegth of the string.</remarks> Public Function WriteToPrinter(ByVal data As String) As Integer Dim pcWritten As Integer = 0 PrintDirect.WritePrinter(lhPrinter, data, data.Length - 1, pcWritten) Return pcWritten End Function Public Sub EndPage() PrintDirect.EndPagePrinter(lhPrinter) End Sub Public Sub CloseDocument() PrintDirect.EndDocPrinter(lhPrinter) End Sub Public Sub ClosePrint() PrintDirect.ClosePrinter(lhPrinter) End Sub ''' <summary> ''' Opens a connection to a printer and starts a new document. ''' </summary> ''' <returns>If false the connection could not be established. </returns> ''' <remarks></remarks> Public Function Open() As Boolean Dim rtn_val As Boolean = False rtn_val = OpenPrint() If rtn_val Then OpenDocument() End If Return rtn_val End Function ''' <summary> ''' Closes the document and closes the connection to the printer. ''' </summary> ''' <remarks></remarks> Public Sub Close() CloseDocument() ClosePrint() End Sub End Class End Class 'PrintDirect Here is how I print my file. I'm simple printing the PCL Masks, to show proof of concept. But I can't even do that. I can effectively create PCL and send it the printer without reading the file and it works fine... Plus I get mixed results with different stream reader text encoding as well. Dim pJob As New PrintDirect.PrintJob pJob.DocumentName = " test doc" pJob.DocumentDataType = PrintDirect.PrintJob.PrintDataType.RAW pJob.PrinterName = sPrinter.GetDevicePath '//This is where you'd stick your device name, sPrinter stands for Selected Printer from a dropdown (combobox). 'pJob.DocumentOutputFile = "C:\temp\test-spool.txt" If Not pJob.OpenPrint() Then MsgBox("Unable to connect to " & pJob.PrinterName, MsgBoxStyle.OkOnly, "Print Error") Exit Sub End If pJob.OpenDocument() pJob.StartPage() Dim sr As New IO.StreamReader(Me.txtFile.Text, Text.Encoding.ASCII) '//I've got best results with ASCII before, but only mized. Dim line As String = sr.ReadLine 'Fix for fly code on first run 'If line = 27 Then line = PrintDirect.PrintJob.PCL_Control_Character Do While (Not line Is Nothing) pJob.WriteToPrinter(line) line = sr.ReadLine Loop 'pJob.WriteToPrinter(ControlChars.FormFeed) pJob.EndPage() pJob.CloseDocument() sr.Close() sr.Dispose() sr = Nothing pJob.Close() I was able to get to print the mask, in the morning... now I'm getting strange printer characters scattered through 5 pages... I'm totally clueless. I must have changed something or the printer is at fault. You can access my test Check Mask, here http://kscserver.com/so/chk_mask.zip .

    Read the article

  • Searching for Windows User SID's in C#

    - by Ubiquitous Che
    Context Context first - issues I'm trying to resolve are below. One of our clients has asked as to quote how long it would take for us to improve one of our applications. This application currently provides basic user authentication in the form of username/password combinations. This client would like the ability for their employees to log-in using the details of whatever Windows User account is currently logged in at the time of running the application. It's not a deal-breaker if I tell them know - but the client might be willing to pay the costs of development to add this feature to the application. It's worth looking into. Based on my hunting around, it seems like storing the user login details against Domain\Username will be problematic if those details are changed. But Windows User SID's aren't supposed to change at all. I've got the impression that it would be best to record Windows Users by SID - feel free to relieve me of that if I'm wrong. I've been having a fiddle with some Windows API calls. From within C#, grabbing the current user's SID is easy enough. I can already take any user's SID and process it using LookupAccountSid to get username and domain for display purposes. For the interested, my code for this is at the end of this post. That's just the tip of the iceberg, however. The two issues below are completely outside my experience. Not only do I not know how to implement them - I don't even known how to find out how to implement them, or what the pitfalls are on various systems. Any help getting myself aimed in the right direction would be very much appreciated. Issue 1) Getting hold of the local user at runtime is meaningless if that user hasn't been granted access to the application. We will need to add a new section to our application's 'administrator console' for adding Windows Users (or groups) and assigning within-app permissions against those users. Something like an 'Add Windows User Login' button that will raise a pop-up window that will allow the user to search for available Windows User accounts on the network (not just the local machine) to be added to the list of available application logins. If there's already a component in .NET or Windows that I can shanghai into doing this for me, it would make me a very happy man. Issue 2) I also want to know how to take a given Windows User SID and check it against a given Windows User Group (probably taken from a database). I'm not sure how to get started with this one either, though I expect it to be easier than the issue above. For the Interested [STAThread] static void Main(string[] args) { MessageBox.Show(WindowsUserManager.GetAccountNameFromSID(WindowsIdentity.GetCurrent().User.Value)); MessageBox.Show(WindowsUserManager.GetAccountNameFromSID("S-1-5-21-57989841-842925246-1957994488-1003")); } public static class WindowsUserManager { public static string GetAccountNameFromSID(string SID) { try { StringBuilder name = new StringBuilder(); uint cchName = (uint)name.Capacity; StringBuilder referencedDomainName = new StringBuilder(); uint cchReferencedDomainName = (uint)referencedDomainName.Capacity; WindowsUserManager.SID_NAME_USE sidUse; int err = (int)ESystemError.ERROR_SUCCESS; if (!WindowsUserManager.LookupAccountSid(null, SID, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse)) { err = Marshal.GetLastWin32Error(); if (err == (int)ESystemError.ERROR_INSUFFICIENT_BUFFER) { name.EnsureCapacity((int)cchName); referencedDomainName.EnsureCapacity((int)cchReferencedDomainName); err = WindowsUserManager.LookupAccountSid(null, SID, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse) ? (int)ESystemError.ERROR_SUCCESS : Marshal.GetLastWin32Error(); } } if (err != (int)ESystemError.ERROR_SUCCESS) throw new ApplicationException(String.Format("Could not retrieve acount name from SID. {0}", SystemExceptionManager.GetDescription(err))); return String.Format(@"{0}\{1}", referencedDomainName.ToString(), name.ToString()); } catch (Exception ex) { if (ex is ApplicationException) throw ex; throw new ApplicationException("Could not retrieve acount name from SID", ex); } } private enum SID_NAME_USE { SidTypeUser = 1, SidTypeGroup, SidTypeDomain, SidTypeAlias, SidTypeWellKnownGroup, SidTypeDeletedAccount, SidTypeInvalid, SidTypeUnknown, SidTypeComputer } [DllImport("advapi32.dll", EntryPoint = "GetLengthSid", CharSet = CharSet.Auto)] private static extern int GetLengthSid(IntPtr pSID); [DllImport("advapi32.dll", SetLastError = true)] private static extern bool ConvertStringSidToSid( string StringSid, out IntPtr ptrSid); [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern bool LookupAccountSid( string lpSystemName, [MarshalAs(UnmanagedType.LPArray)] byte[] Sid, StringBuilder lpName, ref uint cchName, StringBuilder ReferencedDomainName, ref uint cchReferencedDomainName, out SID_NAME_USE peUse); private static bool LookupAccountSid( string lpSystemName, string stringSid, StringBuilder lpName, ref uint cchName, StringBuilder ReferencedDomainName, ref uint cchReferencedDomainName, out SID_NAME_USE peUse) { byte[] SID = null; IntPtr SID_ptr = IntPtr.Zero; try { WindowsUserManager.ConvertStringSidToSid(stringSid, out SID_ptr); int err = SID_ptr == IntPtr.Zero ? Marshal.GetLastWin32Error() : (int)ESystemError.ERROR_SUCCESS; if (SID_ptr == IntPtr.Zero || err != (int)ESystemError.ERROR_SUCCESS) throw new ApplicationException(String.Format("'{0}' could not be converted to a SID byte array. {1}", stringSid, SystemExceptionManager.GetDescription(err))); int size = (int)GetLengthSid(SID_ptr); SID = new byte[size]; Marshal.Copy(SID_ptr, SID, 0, size); } catch (Exception ex) { if (ex is ApplicationException) throw ex; throw new ApplicationException(String.Format("'{0}' could not be converted to a SID byte array. {1}.", stringSid, ex.Message), ex); } finally { // Always want to release the SID_ptr (if it exists) to avoid memory leaks. if (SID_ptr != IntPtr.Zero) Marshal.FreeHGlobal(SID_ptr); } return WindowsUserManager.LookupAccountSid(lpSystemName, SID, lpName, ref cchName, ReferencedDomainName, ref cchReferencedDomainName, out peUse); } }

    Read the article

  • WinRT WebView and Cookies

    - by javarg
    Turns out that WebView Control in WinRT is much more limited than it’s counterpart in WPF/Silverlight. There are some great articles out there in how to extend the control in order for it to support navigation events and some other features. For a personal project I'm working on, I needed to grab cookies a Web Site generated for the user. Basically, after a user authenticated to a Web Site I needed to get the authentication cookies and generate some extra requests on her behalf. In order to do so, I’ve found this great article about a similar case using SharePoint and Azure ACS. The secret is to use a p/invoke to native InternetGetCookieEx to get cookies for the current URL displayed in the WebView control.   void WebView_LoadCompleted(object sender, NavigationEventArgs e) { var urlPattern = "http://someserver.com/somefolder"; if (e.Uri.ToString().StartsWith(urlPattern)) { var cookies = InternetGetCookieEx(e.Uri.ToString()); // Do something with the cookies } } static string InternetGetCookieEx(string url) { uint sizeInBytes = 0; // Gets capacity length first InternetGetCookieEx(url, null, null, ref sizeInBytes, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero); uint bufferCapacityInChars = (uint)Encoding.Unicode.GetMaxCharCount((int)sizeInBytes); // Now get cookie data var cookieData = new StringBuilder((int)bufferCapacityInChars); InternetGetCookieEx(url, null, cookieData, ref bufferCapacityInChars, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero); return cookieData.ToString(); }   Function import using p/invoke follows: const int INTERNET_COOKIE_HTTPONLY = 0x00002000; [DllImport("wininet.dll", CharSet = CharSet.Unicode, SetLastError = true)] static extern bool InternetGetCookieEx(string pchURL, string pchCookieName, StringBuilder pchCookieData, ref System.UInt32 pcchCookieData, int dwFlags, IntPtr lpReserved); Enjoy!

    Read the article

  • My application had a WindowsIdentity crisis

    - by Brian Donahue
    The project I have been working on this week to test computer environments needs to do various actions as a user other than the one running the application. For instance, it looks up an installed Windows Service, finds out who the startup user is, and tries to connect to a database as that Windows user. Later on, it will need to access a file in the context of the currently logged-in user. With ASP .NET, this is super-easy: just go into Web.Config and set up the "identity impersonate" node, which can either impersonate a named user or the one who had logged into the website if authentication was enabled. With Windows applications, this is not so straightforward. There may be something I am overlooking, but the limitation seems to be that you can only change the security context on the current thread: any threads spawned by the impersonated thread also inherit the impersonated credentials. Impersonation is easy enough to do, once you figure out how. Here is my code for impersonating a user on the current thread:         using System;         using System.ComponentModel;         using System.Runtime.InteropServices;         using System.Security.Principal;         public class ImpersonateUser         {                 IntPtr userHandle;   [DllImport("advapi32.dll", SetLastError = true)]                 static extern bool LogonUser(                         string lpszUsername,                         string lpszDomain,                         string lpszPassword,                         LogonType dwLogonType,                         LogonProvider dwLogonProvider,                         out IntPtr phToken                         );                     [DllImport("kernel32.dll", SetLastError = true)]                 static extern bool CloseHandle(IntPtr hHandle);                     enum LogonType : int                 {                         Interactive = 2,                         Network = 3,                         Batch = 4,                         Service = 5,                         NetworkCleartext = 8,                         NewCredentials = 9,                 }                     enum LogonProvider : int                 {                         Default = 0,                 }                 public static WindowsImpersonationContext Impersonate(string user, string domain, string password)                 {   IntPtr userHandle = IntPtr.Zero;                         bool loggedOn = LogonUser(                                 user,                                 domain,                                 password,                                 LogonType.Interactive,                                 LogonProvider.Default,                                 out userHandle);                               if (!loggedOn)                         throw new Win32Exception(Marshal.GetLastWin32Error());                           WindowsIdentity identity = new WindowsIdentity(userHandle);                         WindowsPrincipal principal = new WindowsPrincipal(identity);                         System.Threading.Thread.CurrentPrincipal = principal;                         return identity.Impersonate();   }         }   /* Call impersonation */ ImpersonateUser.Impersonate("UserName","DomainName","Password"); /* When you want to go back to the original user */ WindowsIdentity.Impersonate(IntPtr.Zero); When you want to stop impersonating, you can call Impersonate() again with a null pointer. This will allow you to simulate a variety of different Windows users from the same applicaiton.

    Read the article

  • c# SendMessage and Skype woes

    - by Xcelled194
    I'm trying to create an add-on to Skype with C#. I don't want to use Skype4COM, as I'd like the experience with messages and such. Unfortunately, the messages are tripping me up. I've got the pumps and such set up. They all work, and my app successfully sends the "APIDiscover" message to Skype, gets a "PendingAuth" response and then the "AttachSuccess" message. However, when I try to send "ping" to Skype (to which it should reply "pong") nothing happens. The return code from SendMessage is 0 but Marshall.GetLastWin32Error is 1400 (Invalid handle). The handle was returned with the AttachSuccess method. The equivalent C++ code does work, so I'm at a loss. First is the C++ code I'm using as a guide: Here's the (cut down) message pump. You can ignore everything but where I put the //<---- static LRESULT APIENTRY SkypeAPITest_Windows_WindowProc( HWND hWindow, UINT uiMessage, WPARAM uiParam, LPARAM ulParam) { LRESULT lReturnCode; bool fIssueDefProc; lReturnCode=0; fIssueDefProc=false; switch(uiMessage) { case WM_COPYDATA: if( hGlobal_SkypeAPIWindowHandle==(HWND)uiParam ) { PCOPYDATASTRUCT poCopyData=(PCOPYDATASTRUCT)ulParam; printf( "Message from Skype(%u): %.*s\n", poCopyData->dwData, poCopyData->cbData, poCopyData->lpData); lReturnCode=1; } break; default: if( uiMessage==uiGlobal_MsgID_SkypeControlAPIAttach ) { switch(ulParam) { case SKYPECONTROLAPI_ATTACH_SUCCESS: printf("!!! Connected; to terminate issue #disconnect\n"); hGlobal_SkypeAPIWindowHandle=(HWND)uiParam;//<---- Right here is where we receive the handle from Skype. break; } if( fIssueDefProc ) lReturnCode=DefWindowProc( hWindow, uiMessage, uiParam, ulParam); return(lReturnCode); } and this is the (again dumbed down) "sending message" code void __cdecl Global_InputProcessingThread(void *) { static char acInputRow[1024]; bool fProcessed; if( SendMessageTimeout( HWND_BROADCAST, uiGlobal_MsgID_SkypeControlAPIDiscover, (WPARAM)hInit_MainWindowHandle, 0, SMTO_ABORTIFHUNG, 1000, NULL)!=0 ) { while(Global_Console_ReadRow( acInputRow, sizeof(acInputRow)-1)) { if( fProcessed==false && hGlobal_SkypeAPIWindowHandle!=NULL ) { COPYDATASTRUCT oCopyData; // send command to skype oCopyData.dwData=0; oCopyData.lpData=acInputRow; oCopyData.cbData=strlen(acInputRow)+1; if( oCopyData.cbData!=1 ) { if( SendMessage( hGlobal_SkypeAPIWindowHandle, WM_COPYDATA, (WPARAM)hInit_MainWindowHandle, (LPARAM)&oCopyData)==FALSE ) { hGlobal_SkypeAPIWindowHandle=NULL; printf("!!! Disconnected\n"); } } } } } SendMessage( hInit_MainWindowHandle, WM_CLOSE, 0, 0); SetEvent(hGlobal_ThreadShutdownEvent); fGlobal_ThreadRunning=false; } And now here's my C# public bool PreFilterMessage(ref Message m) { Console.WriteLine(m.ToString()); if (m.Msg == WM_COPYDATA && SkypeAPIWindowHandle == m.WParam) { SkypeMessage(m); return true; } if (m.Msg == MsgApiAttach) { switch (m.LParam.ToInt32()) { case (int)SkypeControlAPIAttach.SUCCESS: SkypeAPIWindowHandle = m.WParam; //Here's where we set the Skype Handle AttachSuccess(m); return true; } } return false; //Defer all other messages } And here is my DLL import and Sending code [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)] static extern IntPtr SendMessageA(IntPtr hWnd, UInt32 Msg, IntPtr wParam, ref MsgHelper.COPYDATASTRUCT lParam); public static void Command(string c) { if (c.Last() != '\0') c += "\0"; //Make string null terminated Console.WriteLine(); MsgHelper.COPYDATASTRUCT cda = new MsgHelper.COPYDATASTRUCT(); cda.dwData = new IntPtr(0); cda.lpData = c; cda.cbData = c.Length + 1; Marshal.GetLastWin32Error(); //Clear last error Console.WriteLine(SendMessageA(mHelper.SkypeAPIWindowHandle, MsgHelper.WM_COPYDATA, IntPtr.Zero, ref cda)); Console.WriteLine(Marshal.GetLastWin32Error()); } COPYDATASTRUCT is: public struct COPYDATASTRUCT { public IntPtr dwData; public int cbData; [MarshalAs(UnmanagedType.LPStr)] public string lpData; } I think that's everything. Let me know if I forgot something. Any ideas why I'm getting the 1400?

    Read the article

  • Deserializing Metafile

    - by Kildareflare
    I have an application that works with Enhanced Metafiles. I am able to create them, save them to disk as .emf and load them again no problem. I do this by using the gdi32.dll methods and the DLLImport attribute. However, to enable Version Tolerant Serialization I want to save the metafile in an object along with other data. This essentially means that I need to serialize the metafile data as a byte array and then deserialize it again in order to reconstruct the metafile. The problem I have is that the deserialized data would appear to be corrupted in some way, since the method that I use to reconstruct the Metafile raises a "Parameter not valid exception". At the very least the pixel format and resolutions have changed. Code use is below. [DllImport("gdi32.dll")] public static extern uint GetEnhMetaFileBits(IntPtr hemf, uint cbBuffer, byte[] lpbBuffer); [DllImport("gdi32.dll")] public static extern IntPtr SetEnhMetaFileBits(uint cbBuffer, byte[] lpBuffer); [DllImport("gdi32.dll")] public static extern bool DeleteEnhMetaFile(IntPtr hemf); The application creates a metafile image and passes it to the method below. private byte[] ConvertMetaFileToByteArray(Image image) { byte[] dataArray = null; Metafile mf = (Metafile)image; IntPtr enhMetafileHandle = mf.GetHenhmetafile(); uint bufferSize = GetEnhMetaFileBits(enhMetafileHandle, 0, null); if (enhMetafileHandle != IntPtr.Zero) { dataArray = new byte[bufferSize]; GetEnhMetaFileBits(enhMetafileHandle, bufferSize, dataArray); } DeleteEnhMetaFile(enhMetafileHandle); return dataArray; } At this point the dataArray is inserted into an object and serialized using a BinaryFormatter. The saved file is then deserialized again using a BinaryFormatter and the dataArray retrieved from the object. The dataArray is then used to reconstruct the original Metafile using the following method. public static Image ConvertByteArrayToMetafile(byte[] data) { Metafile mf = null; try { IntPtr hemf = SetEnhMetaFileBits((uint)data.Length, data); mf = new Metafile(hemf, true); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } return (Image)mf; } The reconstructed metafile is then saved saved to disk as a .emf (Model) at which point it can be accessed by the Presenter for display. private static void SaveFile(Image image, String filepath) { try { byte[] buffer = ConvertMetafileToByteArray(image); File.WriteAllBytes(filepath, buffer); //will overwrite file if it exists } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } } The problem is that the save to disk fails. If this same method is used to save the original Metafile before it is serialized everything is OK. So something is happening to the data during serialization/deserializtion. Indeed if I check the Metafile properties in the debugger I can see that the ImageFlags, PropertyID, resolution and pixelformats change. Original Format32bppRgb changes to Format32bppArgb Original Resolution 81 changes to 96 I've trawled though google and SO and this has helped me get this far but Im now stuck. Does any one have enough experience with Metafiles / serialization to help..? EDIT: If I serialize/deserialize the byte array directly (without embedding in another object) I get the same problem.

    Read the article

  • Simplify CASE in VB.net code

    - by StealthRT
    Hey all, i am looking here to see if anyone would have a better way to acomplish this task below in less code. Select Case mainMenu.theNumOpened Case 1 Me.Text = "NBMsg1" Me.SetDesktopLocation(My.Computer.Screen.WorkingArea.Width - 302, 5) Case 2 Me.Text = "NBMsg2" Dim hwnd As IntPtr = FindWindow(vbNullString, "NBMsg1") SetWindowPos(hwnd, 0, My.Computer.Screen.WorkingArea.Width - 302, Me.Height + 10, 0, 0, 1) Me.SetDesktopLocation(My.Computer.Screen.WorkingArea.Width - 302, 5) Case 3 Me.Text = "NBMsg3" Dim hwnd As IntPtr = FindWindow(vbNullString, "NBMsg2") SetWindowPos(hwnd, 0, My.Computer.Screen.WorkingArea.Width - 302, Me.Height + 10, 0, 0, 1) hwnd = FindWindow(vbNullString, "NBMsg1") SetWindowPos(hwnd, 0, My.Computer.Screen.WorkingArea.Width - 302, (Me.Height * 2) + 15, 0, 0, 1) Me.SetDesktopLocation(My.Computer.Screen.WorkingArea.Width - 302, 5) Case 4 Me.Text = "NBMsg4" Dim hwnd As IntPtr = FindWindow(vbNullString, "NBMsg3") SetWindowPos(hwnd, 0, My.Computer.Screen.WorkingArea.Width - 302, Me.Height + 10, 0, 0, 1) hwnd = FindWindow(vbNullString, "NBMsg2") SetWindowPos(hwnd, 0, My.Computer.Screen.WorkingArea.Width - 302, (Me.Height * 2) + 15, 0, 0, 1) hwnd = FindWindow(vbNullString, "NBMsg1") SetWindowPos(hwnd, 0, My.Computer.Screen.WorkingArea.Width - 302, (Me.Height * 3) + 20, 0, 0, 1) Me.SetDesktopLocation(My.Computer.Screen.WorkingArea.Width - 302, 5) Case 5 Me.Text = "NBMsg5" Dim hwnd As IntPtr = FindWindow(vbNullString, "NBMsg4") SetWindowPos(hwnd, 0, My.Computer.Screen.WorkingArea.Width - 302, Me.Height + 10, 0, 0, 1) hwnd = FindWindow(vbNullString, "NBMsg3") SetWindowPos(hwnd, 0, My.Computer.Screen.WorkingArea.Width - 302, (Me.Height * 2) + 15, 0, 0, 1) hwnd = FindWindow(vbNullString, "NBMsg2") SetWindowPos(hwnd, 0, My.Computer.Screen.WorkingArea.Width - 302, (Me.Height * 3) + 20, 0, 0, 1) hwnd = FindWindow(vbNullString, "NBMsg1") SetWindowPos(hwnd, 0, My.Computer.Screen.WorkingArea.Width - 302, (Me.Height * 4) + 25, 0, 0, 1) Me.SetDesktopLocation(My.Computer.Screen.WorkingArea.Width - 302, 5) Case 6 Me.Text = "NBMsg6" Dim hwnd As IntPtr = FindWindow(vbNullString, "NBMsg5") SetWindowPos(hwnd, 0, My.Computer.Screen.WorkingArea.Width - 302, Me.Height + 10, 0, 0, 1) hwnd = FindWindow(vbNullString, "NBMsg4") SetWindowPos(hwnd, 0, My.Computer.Screen.WorkingArea.Width - 302, (Me.Height * 2) + 15, 0, 0, 1) hwnd = FindWindow(vbNullString, "NBMsg3") SetWindowPos(hwnd, 0, My.Computer.Screen.WorkingArea.Width - 302, (Me.Height * 3) + 20, 0, 0, 1) hwnd = FindWindow(vbNullString, "NBMsg2") SetWindowPos(hwnd, 0, My.Computer.Screen.WorkingArea.Width - 302, (Me.Height * 4) + 25, 0, 0, 1) hwnd = FindWindow(vbNullString, "NBMsg1") SetWindowPos(hwnd, 0, My.Computer.Screen.WorkingArea.Width - 302, (Me.Height * 5) + 30, 0, 0, 1) Me.SetDesktopLocation(My.Computer.Screen.WorkingArea.Width - 302, 5) Case Else Me.Close() Me.Dispose() End Select What it does is pass to it now many windows are currently already opened. So if one then of course it goes to case 1. If there are 2 opened then it moves the oldest down and puts the newest on top. etc etc. I have set it so that a max of 6 boxes can only be opened at one time. If anyone knows how i could also "slide" them down (kinda like an effect of jQuery) then that would also be, well awesome to know! :o) Any help/suggestions would be great! :o) David

    Read the article

  • cannot evaluate expression because a native frame is on top of the call stack and system.accessviolationexception

    - by Joseph
    I have this code using c#. public partial class MainForm : Form { private CvCapture VideoCapture; private IplImage frame; private IplImage imgMain; public MainForm() { InitializeComponent(); } private void btnVideo_Click(object sender, EventArgs e) { double vidWidth, vidHeight; try { VideoCapture = highgui.CvCreateCameraCapture(0); } catch (Exception except) { MessageBox.Show(except.Message); } if (btnVideo.Text.CompareTo("Start Video") == 0) { if (VideoCapture.ptr == IntPtr.Zero) { MessageBox.Show("badtrip ah!!!"); return; } btnVideo.Text = "Stop Video"; highgui.CvSetCaptureProperty(ref VideoCapture, highgui.CV_CAP_PROP_FRAME_WIDTH, 640); highgui.CvSetCaptureProperty(ref VideoCapture, highgui.CV_CAP_PROP_FRAME_HEIGHT, 480); highgui.CvQueryFrame(ref VideoCapture); vidWidth = highgui.cvGetCaptureProperty(VideoCapture, highgui.CV_CAP_PROP_FRAME_WIDTH); vidHeight = highgui.cvGetCaptureProperty(VideoCapture, highgui.CV_CAP_PROP_FRAME_HEIGHT); picBoxMain.Width = (int)vidWidth; picBoxMain.Height = (int)vidHeight; timerGrab.Enabled = true; timerGrab.Interval = 42; timerGrab.Start(); } else { btnVideo.Text = "Start Video"; timerGrab.Enabled = false; if (VideoCapture.ptr == IntPtr.Zero) { highgui.CvReleaseCapture(ref VideoCapture); VideoCapture.ptr = IntPtr.Zero; } } } private void timerGrab_Tick(object sender, EventArgs e) { try { frame = highgui.CvQueryFrame(ref VideoCapture); if (frame.ptr == IntPtr.Zero) { timerGrab.Stop(); MessageBox.Show("??"); return; } imgMain = cxcore.CvCreateImage(cxcore.CvGetSize(ref frame), 8, 3); picBoxMain.Image = highgui.ToBitmap(imgMain, false); cxcore.CvReleaseImage(ref imgMain); //cxcore.CvReleaseImage(ref frame); } catch (Exception excpt) { MessageBox.Show(excpt.Message); } } } The problem is after i break all and step through the debugger the program stops at a certain code. the code where it stops is here: frame = highgui.CvQueryFrame(ref VideoCapture); the error is that it says that cannot evaluate expression because a native frame is on top of the call stack. and then when i try to shift+F11 it. there is another error saying that system.accessviolationexception. the stack trace says that: at System.Runtime.InteropServices.Marshal.CopyToManaged(IntPtr source, Object destination, Int32 startIndex, Int32 length) at CxCore.IplImage.get_ImageDataDb()

    Read the article

  • Use native HBitmap in C# while preserving alpha channel/transparency. Please check this code, it works on my computer...

    - by David
    Let's say I get a HBITMAP object/handle from a native Windows function. I can convert it to a managed bitmap using Bitmap.FromHbitmap(nativeHBitmap), but if the native image has transparency information (alpha channel), it is lost by this conversion. There are a few questions on Stack Overflow regarding this issue. Using information from the first answer of this question (How to draw ARGB bitmap using GDI+?), I wrote a piece of code that I've tried and it works. It basically gets the native HBitmap width, height and the pointer to the location of the pixel data using GetObject and the BITMAP structure, and then calls the managed Bitmap constructor: Bitmap managedBitmap = new Bitmap(bitmapStruct.bmWidth, bitmapStruct.bmHeight, bitmapStruct.bmWidth * 4, PixelFormat.Format32bppArgb, bitmapStruct.bmBits); As I understand (please correct me if I'm wrong), this does not copy the actual pixel data from the native HBitmap to the managed bitmap, it simply points the managed bitmap to the pixel data from the native HBitmap. And I don't draw the bitmap here on another Graphics (DC) or on another bitmap, to avoid unnecessary memory copying, especially for large bitmaps. I can simply assign this bitmap to a PictureBox control or the the Form BackgroundImage property. And it works, the bitmap is displayed correctly, using transparency. When I no longer use the bitmap, I make sure the BackgroundImage property is no longer pointing to the bitmap, and I dispose both the managed bitmap and the native HBitmap. The Question: Can you tell me if this reasoning and code seems correct. I hope I will not get some unexpected behaviors or errors. And I hope I'm freeing all the memory and objects correctly. private void Example() { IntPtr nativeHBitmap = IntPtr.Zero; /* Get the native HBitmap object from a Windows function here */ // Create the BITMAP structure and get info from our nativeHBitmap NativeMethods.BITMAP bitmapStruct = new NativeMethods.BITMAP(); NativeMethods.GetObjectBitmap(nativeHBitmap, Marshal.SizeOf(bitmapStruct), ref bitmapStruct); // Create the managed bitmap using the pointer to the pixel data of the native HBitmap Bitmap managedBitmap = new Bitmap( bitmapStruct.bmWidth, bitmapStruct.bmHeight, bitmapStruct.bmWidth * 4, PixelFormat.Format32bppArgb, bitmapStruct.bmBits); // Show the bitmap this.BackgroundImage = managedBitmap; /* Run the program, use the image */ MessageBox.Show("running..."); // When the image is no longer needed, dispose both the managed Bitmap object and the native HBitmap this.BackgroundImage = null; managedBitmap.Dispose(); NativeMethods.DeleteObject(nativeHBitmap); } internal static class NativeMethods { [StructLayout(LayoutKind.Sequential)] public struct BITMAP { public int bmType; public int bmWidth; public int bmHeight; public int bmWidthBytes; public ushort bmPlanes; public ushort bmBitsPixel; public IntPtr bmBits; } [DllImport("gdi32", CharSet = CharSet.Auto, EntryPoint = "GetObject")] public static extern int GetObjectBitmap(IntPtr hObject, int nCount, ref BITMAP lpObject); [DllImport("gdi32.dll")] internal static extern bool DeleteObject(IntPtr hObject); }

    Read the article

  • Is there an easier way of creating a registry volatile subkey in .net?

    - by Simon
    So far I have the below which is taken from http://www.danielmoth.com/Blog/volatile-registrykey.aspx public static class RegistryHelper { public static RegistryKey CreateVolatileSubKey(RegistryKey rk, string subkey, RegistryKeyPermissionCheck permissionCheck) { var rk2 = rk.GetType(); const BindingFlags bfStatic = BindingFlags.NonPublic | BindingFlags.Static; const BindingFlags bfInstance = BindingFlags.NonPublic | BindingFlags.Instance; rk2.GetMethod("ValidateKeyName", bfStatic).Invoke(null, new object[] { subkey }); rk2.GetMethod("ValidateKeyMode", bfStatic).Invoke(null, new object[] { permissionCheck }); rk2.GetMethod("EnsureWriteable", bfInstance).Invoke(rk, null); subkey = (string)rk2.GetMethod("FixupName", bfStatic).Invoke(null, new object[] { subkey }); if (!(bool)rk2.GetField("remoteKey", bfInstance).GetValue(rk)) { var key = (RegistryKey)rk2.GetMethod("InternalOpenSubKey", bfInstance, null, new[] { typeof(string), typeof(bool) }, null).Invoke(rk, new object[] { subkey, permissionCheck != RegistryKeyPermissionCheck.ReadSubTree }); if (key != null) { rk2.GetMethod("CheckSubKeyWritePermission", bfInstance).Invoke(rk, new object[] { subkey }); rk2.GetMethod("CheckSubTreePermission", bfInstance).Invoke(rk, new object[] { subkey, permissionCheck }); rk2.GetField("checkMode", bfInstance).SetValue(key, permissionCheck); return key; } } rk2.GetMethod("CheckSubKeyCreatePermission", bfInstance).Invoke(rk, new object[] { subkey }); int lpdwDisposition; IntPtr hkResult; var srh = Type.GetType("Microsoft.Win32.SafeHandles.SafeRegistryHandle"); var temp = rk2.GetField("hkey", bfInstance).GetValue(rk); var rkhkey = (SafeHandleZeroOrMinusOneIsInvalid)temp; var getregistrykeyaccess = (int)rk2.GetMethod("GetRegistryKeyAccess", bfStatic, null, new[] { typeof(bool) }, null).Invoke(null, new object[] { permissionCheck != RegistryKeyPermissionCheck.ReadSubTree }); var errorCode = RegCreateKeyEx(rkhkey, subkey, 0, null, 1, getregistrykeyaccess, IntPtr.Zero, out hkResult, out lpdwDisposition); var keyNameField = rk2.GetField("keyName", bfInstance); var rkkeyName = (string)keyNameField.GetValue(rk); if (errorCode == 0 && hkResult.ToInt32() > 0) { var rkremoteKey = (bool)rk2.GetField("remoteKey", bfInstance).GetValue(rk); var hkResult2 = srh.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(IntPtr), typeof(bool) }, null).Invoke(new object[] { hkResult, true }); var key2 = (RegistryKey)rk2.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { hkResult2.GetType(), typeof(bool), typeof(bool), typeof(bool), typeof(bool) }, null).Invoke(new[] { hkResult2, permissionCheck != RegistryKeyPermissionCheck.ReadSubTree, false, rkremoteKey, false }); rk2.GetMethod("CheckSubTreePermission", bfInstance).Invoke(rk, new object[] { subkey, permissionCheck }); rk2.GetField("checkMode", bfInstance).SetValue(key2, permissionCheck); if (subkey.Length == 0) { keyNameField.SetValue(key2, rkkeyName); } else { keyNameField.SetValue(key2, rkkeyName + @"\" + subkey); } key2.Close(); return rk.OpenSubKey(subkey, true); } if (errorCode != 0) rk2.GetMethod("Win32Error", bfInstance).Invoke(rk, new object[] { errorCode, rkkeyName + @"\" + subkey }); return null; } [DllImport("advapi32.dll", CharSet = CharSet.Auto)] private static extern int RegCreateKeyEx(SafeHandleZeroOrMinusOneIsInvalid hKey, string lpSubKey, int reserved, string lpClass, int dwOptions, int samDesigner, IntPtr lpSecurityAttributes, out IntPtr hkResult, out int lpdwDisposition); } Which works but is fairly ugly. Is there a better way?

    Read the article

  • check if directory exists c#

    - by Ant
    I am trying to see if a directory exists based on an input field from the user. When the user types in the path, I want to check if the path actually exists. I have some c# code already. It returns 1 for any local path, but always returns 0 when I am checking a network path. static string checkValidPath(string path) { //Insert your code that runs under the security context of the authenticating user here. using (ImpersonateUser user = new ImpersonateUser(user, "", password)) { //DirectoryInfo d = new DirectoryInfo(quotelessPath); bool doesExist = Directory.Exists(path); //if (d.Exists) if(doesExist) { user.Dispose(); return "1"; } else { user.Dispose(); return "0"; } } } public class ImpersonateUser : IDisposable { [DllImport("advapi32.dll", SetLastError = true)] private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken); [DllImport("kernel32", SetLastError = true)] private static extern bool CloseHandle(IntPtr hObject); private IntPtr userHandle = IntPtr.Zero; private WindowsImpersonationContext impersonationContext; public ImpersonateUser(string user, string domain, string password) { if (!string.IsNullOrEmpty(user)) { // Call LogonUser to get a token for the user bool loggedOn = LogonUser(user, domain, password, 9 /*(int)LogonType.LOGON32_LOGON_NEW_CREDENTIALS*/, 3 /*(int)LogonProvider.LOGON32_PROVIDER_WINNT50*/, out userHandle); if (!loggedOn) throw new Win32Exception(Marshal.GetLastWin32Error()); // Begin impersonating the user impersonationContext = WindowsIdentity.Impersonate(userHandle); } } public void Dispose() { if (userHandle != IntPtr.Zero) CloseHandle(userHandle); if (impersonationContext != null) impersonationContext.Undo(); } } Any help is appreciated. Thanks! EDIT 3: updated code to use BrokenGlass's impersonation functions. However, I need to initialize "password" to something... EDIT 2: I updated the code to try and use impersonation as suggested below. It still fails everytime. I assume I am using impersonation improperly... EDIT: As requested by ChrisF, here is the function that calls the checkValidPath function. Frontend aspx file... $.get('processor.ashx', { a: '7', path: x }, function(o) { alert(o); if (o=="0") { $("#outputPathDivValid").dialog({ title: 'Output Path is not valid! Please enter a path that exists!', width: 500, modal: true, resizable: false, buttons: { 'Close': function() { $(this).dialog('close'); } } }); } }); Backend ashx file... public void ProcessRequest (HttpContext context) { context.Response.Cache.SetExpires(DateTime.Now); string sSid = context.Request["sid"]; switch (context.Request["a"]) {//a bunch of case statements here... case "7": context.Response.Write(checkValidPath(context.Request["path"].ToString())); break;

    Read the article

  • Using Ghostscript in a Webapplication (PDF Thumbnails)

    - by cpt.oneeye
    Hello, i am using the ghostscriptsharp wrapper for c# and ghostscript. I want to generate thumbnails out of pdf-files. Further Information on the sample-code are given here. There are different Methods imported form the ghostscript-c-dll "gsdll32.dll". [DllImport("gsdll32.dll", EntryPoint = "gsapi_new_instance")] private static extern int CreateAPIInstance(out IntPtr pinstance, IntPtr caller_handle); [DllImport("gsdll32.dll", EntryPoint = "gsapi_init_with_args")] private static extern int InitAPI(IntPtr instance, int argc, IntPtr argv); //...and so on I am using the GhostscriptWrapper for generating the thumbnails in a webapplication (.net 2.0). This class uses the methods imported above. protected void Page_Load(object sender, EventArgs e){ GhostscriptWrapper.GeneratePageThumb("c:\\sample.pdf", "c:\\sample.jpg", 1, 100, 100); } When i debug the Web-Application in Visual Studio 2008 by hitting key "F5" it works fine (a new instance of webserver is generated). When i create a WindowsForm Application it works too. The thumbnails get generated. When i access the application with the webbrowser directly (http://localhoast/mywebappliation/..) it doesn't work. No thumbnails are generated. But there is also no exception thrown. I placed the gsdll32.dll in the system32-folder of windows xp. The Ghostscript Runtime is installed too. I have given full access in the IIS-Webproject (.Net 2.0). Does anybody know why i can't access Ghostscript from my webapplication? Are there any security-issues for accessing dll-files on the IIS-Server? Greetings Klaus

    Read the article

  • Greyscale Image from YUV420p data

    - by fergs
    From what I have read on the internet the Y value is the luminance value and can be used to create a grey scale image. The following link: http://www.bobpowell.net/grayscale.htm, has some C# code on working out the luminance of a bitmap image : { Bitmap bm = new Bitmap(source.Width,source.Height); for(int y=0;y<bm.Height;y++) public Bitmap ConvertToGrayscale(Bitmap source) { for(int x=0;x<bm.Width;x++) { Color c=source.GetPixel(x,y); int luma = (int)(c.R*0.3 + c.G*0.59+ c.B*0.11); bm.SetPixel(x,y,Color.FromArgb(luma,luma,luma)); } } return bm; } I have a method that returns the YUV values and have the Y data in a byte array. I have the current piece of code and it is failing on Marshal.Copy – attempted to read or write protected memory. public Bitmap ConvertToGrayscale2(byte[] yuvData, int width, int height) { Bitmap bmp; IntPtr blue = IntPtr.Zero; int inputOffSet = 0; long[] pixels = new long[width * height]; try { for (int y = 0; y < height; y++) { int outputOffSet = y * width; for (int x = 0; x < width; x++) { int grey = yuvData[inputOffSet + x] & 0xff; unchecked { pixels[outputOffSet + x] = UINT_Constant | (grey * INT_Constant); } } inputOffSet += width; } blue = Marshal.AllocCoTaskMem(pixels.Length); Marshal.Copy(pixels, 0, blue, pixels.Length); // fails here : Attempted to read or write protected memory bmp = new Bitmap(width, height, width, PixelFormat.Format24bppRgb, blue); } catch (Exception) { throw; } finally { if (blue != IntPtr.Zero) { Marshal.FreeHGlobal(blue); blue = IntPtr.Zero; } } return bmp; } Any help would be appreciated?

    Read the article

  • App using MonoTouch Core Graphics mysteriously crashes

    - by Stephen Ashley
    My app launches with a view controller and a simple view consisting of a button and a subview. When the user touches the button, the subview is populated with scrollviews that display the column headers, row headers, and cells of a spreadsheet. To draw the cells, I use CGBitmapContext to draw the cells, generate an image, and then put the image into the imageview contained in the scrollview that displays the cells. When I run the app on the iPad, it displays the cells just fine, and the scrollview lets the user scroll around in the spreadsheet without any problems. If the user touches the button a second time, the spreadsheet redraws and continues to work perfectly, If, however, the user touches the button a third time, the app crashes. There is no exception information display in the Application Output window. My first thought was that the successive button pushes were using up all the available memory, so I overrode the DidReceiveMemoryWarning method in the view controller and used a breakpoint to confirm that this method was not getting called. My next thought was that the CGBitmapContext was not getting released and looked for a Monotouch equivalent of Objective C's CGContextRelease() function. The closest I could find was the CGBitmapContext instance method Dispose(), which I called, without solving the problem. In order to free up as much memory as possible (in case I was somehow running out of memory without tripping a warning), I tried forcing garbage collection each time I finished using a CGBitmapContext. This made the problem worse. Now the program would crash moments after displaying the spreadsheet the first time. This caused me to wonder whether the Garbage Collector was somehow collecting something necessary to the continued display of graphics on the screen. I would be grateful for any suggestions on further avenues to investigate for the cause of these crashes. I have included the source code for the SpreadsheetView class. The relevant method is DrawSpreadsheet(), which is called when the button is touched. Thank you for your assistance on this matter. Stephen Ashley public class SpreadsheetView : UIView { public ISpreadsheetMessenger spreadsheetMessenger = null; public UIScrollView cellsScrollView = null; public UIImageView cellsImageView = null; public SpreadsheetView(RectangleF frame) : base() { Frame = frame; BackgroundColor = Constants.backgroundBlack; AutosizesSubviews = true; } public void DrawSpreadsheet() { UInt16 RowHeaderWidth = spreadsheetMessenger.RowHeaderWidth; UInt16 RowHeaderHeight = spreadsheetMessenger.RowHeaderHeight; UInt16 RowCount = spreadsheetMessenger.RowCount; UInt16 ColumnHeaderWidth = spreadsheetMessenger.ColumnHeaderWidth; UInt16 ColumnHeaderHeight = spreadsheetMessenger.ColumnHeaderHeight; UInt16 ColumnCount = spreadsheetMessenger.ColumnCount; // Add the corner UIImageView cornerView = new UIImageView(new RectangleF(0f, 0f, RowHeaderWidth, ColumnHeaderHeight)); cornerView.BackgroundColor = Constants.headingColor; CGColorSpace cornerColorSpace = null; CGBitmapContext cornerContext = null; IntPtr buffer = Marshal.AllocHGlobal(RowHeaderWidth * ColumnHeaderHeight * 4); if (buffer == IntPtr.Zero) throw new OutOfMemoryException("Out of memory."); try { cornerColorSpace = CGColorSpace.CreateDeviceRGB(); cornerContext = new CGBitmapContext (buffer, RowHeaderWidth, ColumnHeaderHeight, 8, 4 * RowHeaderWidth, cornerColorSpace, CGImageAlphaInfo.PremultipliedFirst); cornerContext.SetFillColorWithColor(Constants.headingColor.CGColor); cornerContext.FillRect(new RectangleF(0f, 0f, RowHeaderWidth, ColumnHeaderHeight)); cornerView.Image = UIImage.FromImage(cornerContext.ToImage()); } finally { Marshal.FreeHGlobal(buffer); if (cornerContext != null) { cornerContext.Dispose(); cornerContext = null; } if (cornerColorSpace != null) { cornerColorSpace.Dispose(); cornerColorSpace = null; } } cornerView.Image = DrawBottomRightCorner(cornerView.Image); AddSubview(cornerView); // Add the cellsScrollView cellsScrollView = new UIScrollView (new RectangleF(RowHeaderWidth, ColumnHeaderHeight, Frame.Width - RowHeaderWidth, Frame.Height - ColumnHeaderHeight)); cellsScrollView.ContentSize = new SizeF (ColumnCount * ColumnHeaderWidth, RowCount * RowHeaderHeight); Size iContentSize = new Size((int)cellsScrollView.ContentSize.Width, (int)cellsScrollView.ContentSize.Height); cellsScrollView.BackgroundColor = UIColor.Black; AddSubview(cellsScrollView); CGColorSpace colorSpace = null; CGBitmapContext context = null; CGGradient gradient = null; UIImage image = null; int bytesPerRow = 4 * iContentSize.Width; int byteCount = bytesPerRow * iContentSize.Height; buffer = Marshal.AllocHGlobal(byteCount); if (buffer == IntPtr.Zero) throw new OutOfMemoryException("Out of memory."); try { colorSpace = CGColorSpace.CreateDeviceRGB(); context = new CGBitmapContext (buffer, iContentSize.Width, iContentSize.Height, 8, 4 * iContentSize.Width, colorSpace, CGImageAlphaInfo.PremultipliedFirst); float[] components = new float[] {.75f, .75f, .75f, 1f, .25f, .25f, .25f, 1f}; float[] locations = new float[]{0f, 1f}; gradient = new CGGradient(colorSpace, components, locations); PointF startPoint = new PointF(0f, (float)iContentSize.Height); PointF endPoint = new PointF((float)iContentSize.Width, 0f); context.DrawLinearGradient(gradient, startPoint, endPoint, 0); context.SetLineWidth(Constants.lineWidth); context.BeginPath(); for (UInt16 i = 1; i <= RowCount; i++) { context.MoveTo (0f, iContentSize.Height - i * RowHeaderHeight + (Constants.lineWidth/2)); context.AddLineToPoint((float)iContentSize.Width, iContentSize.Height - i * RowHeaderHeight + (Constants.lineWidth/2)); } for (UInt16 j = 1; j <= ColumnCount; j++) { context.MoveTo((float)j * ColumnHeaderWidth - Constants.lineWidth/2, (float)iContentSize.Height); context.AddLineToPoint((float)j * ColumnHeaderWidth - Constants.lineWidth/2, 0f); } context.StrokePath(); image = UIImage.FromImage(context.ToImage()); } finally { Marshal.FreeHGlobal(buffer); if (gradient != null) { gradient.Dispose(); gradient = null; } if (context != null) { context.Dispose(); context = null; } if (colorSpace != null) { colorSpace.Dispose(); colorSpace = null; } // GC.Collect(); //GC.WaitForPendingFinalizers(); } UIImage finalImage = ActivateCell(1, 1, image); finalImage = ActivateCell(0, 0, finalImage); cellsImageView = new UIImageView(finalImage); cellsImageView.Frame = new RectangleF(0f, 0f, iContentSize.Width, iContentSize.Height); cellsScrollView.AddSubview(cellsImageView); } private UIImage ActivateCell(UInt16 column, UInt16 row, UIImage backgroundImage) { UInt16 ColumnHeaderWidth = (UInt16)spreadsheetMessenger.ColumnHeaderWidth; UInt16 RowHeaderHeight = (UInt16)spreadsheetMessenger.RowHeaderHeight; CGColorSpace cellColorSpace = null; CGBitmapContext cellContext = null; UIImage cellImage = null; IntPtr buffer = Marshal.AllocHGlobal(4 * ColumnHeaderWidth * RowHeaderHeight); if (buffer == IntPtr.Zero) throw new OutOfMemoryException("Out of memory: ActivateCell()"); try { cellColorSpace = CGColorSpace.CreateDeviceRGB(); // Create a bitmap the size of a cell cellContext = new CGBitmapContext (buffer, ColumnHeaderWidth, RowHeaderHeight, 8, 4 * ColumnHeaderWidth, cellColorSpace, CGImageAlphaInfo.PremultipliedFirst); // Paint it white cellContext.SetFillColorWithColor(UIColor.White.CGColor); cellContext.FillRect(new RectangleF(0f, 0f, ColumnHeaderWidth, RowHeaderHeight)); // Convert it to an image cellImage = UIImage.FromImage(cellContext.ToImage()); } finally { Marshal.FreeHGlobal(buffer); if (cellContext != null) { cellContext.Dispose(); cellContext = null; } if (cellColorSpace != null) { cellColorSpace.Dispose(); cellColorSpace = null; } // GC.Collect(); //GC.WaitForPendingFinalizers(); } // Draw the border on the cell image cellImage = DrawBottomRightCorner(cellImage); CGColorSpace colorSpace = null; CGBitmapContext context = null; Size iContentSize = new Size((int)backgroundImage.Size.Width, (int)backgroundImage.Size.Height); buffer = Marshal.AllocHGlobal(4 * iContentSize.Width * iContentSize.Height); if (buffer == IntPtr.Zero) throw new OutOfMemoryException("Out of memory: ActivateCell()."); try { colorSpace = CGColorSpace.CreateDeviceRGB(); // Set up a bitmap context the size of the whole grid context = new CGBitmapContext (buffer, iContentSize.Width, iContentSize.Height, 8, 4 * iContentSize.Width, colorSpace, CGImageAlphaInfo.PremultipliedFirst); // Draw the original grid into the bitmap context.DrawImage(new RectangleF(0f, 0f, iContentSize.Width, iContentSize.Height), backgroundImage.CGImage); // Draw the cell image into the bitmap context.DrawImage(new RectangleF(column * ColumnHeaderWidth, iContentSize.Height - (row + 1) * RowHeaderHeight, ColumnHeaderWidth, RowHeaderHeight), cellImage.CGImage); // Convert the bitmap back to an image backgroundImage = UIImage.FromImage(context.ToImage()); } finally { Marshal.FreeHGlobal(buffer); if (context != null) { context.Dispose(); context = null; } if (colorSpace != null) { colorSpace.Dispose(); colorSpace = null; } // GC.Collect(); //GC.WaitForPendingFinalizers(); } return backgroundImage; } private UIImage DrawBottomRightCorner(UIImage image) { int width = (int)image.Size.Width; int height = (int)image.Size.Height; float lineWidth = Constants.lineWidth; CGColorSpace colorSpace = null; CGBitmapContext context = null; UIImage returnImage = null; IntPtr buffer = Marshal.AllocHGlobal(4 * width * height); if (buffer == IntPtr.Zero) throw new OutOfMemoryException("Out of memory: DrawBottomRightCorner()."); try { colorSpace = CGColorSpace.CreateDeviceRGB(); context = new CGBitmapContext (buffer, width, height, 8, 4 * width, colorSpace, CGImageAlphaInfo.PremultipliedFirst); context.DrawImage(new RectangleF(0f, 0f, width, height), image.CGImage); context.BeginPath(); context.MoveTo(0f, (int)(lineWidth/2f)); context.AddLineToPoint(width - (int)(lineWidth/2f), (int)(lineWidth/2f)); context.AddLineToPoint(width - (int)(lineWidth/2f), height); context.SetLineWidth(Constants.lineWidth); context.SetStrokeColorWithColor(UIColor.Black.CGColor); context.StrokePath(); returnImage = UIImage.FromImage(context.ToImage()); } finally { Marshal.FreeHGlobal(buffer); if (context != null){ context.Dispose(); context = null;} if (colorSpace != null){ colorSpace.Dispose(); colorSpace = null;} // GC.Collect(); //GC.WaitForPendingFinalizers(); } return returnImage; } }

    Read the article

  • GDI RoundRect on Compact Framework: make rounded rectangle's outside transparent.

    - by VansFannel
    Hello! I'm using the RoundRect GDI function to draw a rounded rectangle following this example: .NET CF Custom Control: RoundedGroupBox Because all controls are square, it also draw the corners outside of the rounded rectangle. How can I make this space left outside the rectangle transparent? The OnPaint method is: protected override void OnPaint(PaintEventArgs e) { int outerBrushColor = HelperMethods.ColorToWin32(m_outerColor); int innerBrushColor = HelperMethods.ColorToWin32(this.BackColor); IntPtr hdc = e.Graphics.GetHdc(); try { IntPtr hbrOuter = NativeMethods.CreateSolidBrush(outerBrushColor); IntPtr hOldBrush = NativeMethods.SelectObject(hdc, hbrOuter); NativeMethods.RoundRect(hdc, 0, 0, this.Width, this.Height, m_diametro, m_diametro); IntPtr hbrInner = NativeMethods.CreateSolidBrush(innerBrushColor); NativeMethods.SelectObject(hdc, hbrInner); NativeMethods.RoundRect(hdc, 0, 18, this.Width, this.Height, m_diametro, m_diametro); NativeMethods.SelectObject(hdc, hOldBrush); NativeMethods.DeleteObject(hbrOuter); NativeMethods.DeleteObject(hbrInner); } finally { e.Graphics.ReleaseHdc(hdc); } if (!string.IsNullOrEmpty(m_roundedGroupBoxText)) { Font titleFont = new Font("Tahoma", 9.0F, FontStyle.Bold); Brush titleBrush = new SolidBrush(this.BackColor); try { e.Graphics.DrawString(m_roundedGroupBoxText, titleFont, titleBrush, 14.0F, 2.0F); } finally { titleFont.Dispose(); titleBrush.Dispose(); } } base.OnPaint(e); } An the OnPaintBackground is: protected override void OnPaintBackground(PaintEventArgs e) { if (this.Parent != null) { SolidBrush backBrush = new SolidBrush(this.Parent.BackColor); try { e.Graphics.FillRectangle(backBrush, 0, 0, this.Width, this.Height); } finally { backBrush.Dispose(); } } } Thank you!

    Read the article

  • C# sendkeys problem

    - by user203123
    THe code below I copied from MSDN with a bit of modification: [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr FindWindow(string lpClassName,string lpWindowName); DllImport("User32")] public static extern bool SetForegroundWindow(IntPtr hWnd); int cnt = 0; private void button1_Click(object sender, EventArgs e) { IntPtr calculatorHandle = FindWindow("Notepad", "Untitled - Notepad"); if (calculatorHandle == IntPtr.Zero) { MessageBox.Show("Calculator is not running."); return; } SetForegroundWindow(calculatorHandle); SendKeys.SendWait(cnt.ToString()); SendKeys.SendWait("{ENTER}"); cnt++; SendKeys.Flush(); System.Threading.Thread.Sleep(1000); } The problem is the number sequence in Notepad is not continuously. The first click always results 0 (as expected). but from the second click, the result is unpredictable (but the sequence is still in order, e.g. 3, 4, 5, 10, 14, 15, ....) If I click the button fast enough, I was able to get the result in continuous order (0,1,2,3,4,....) but sometimes it produces more than 2 same numbers (e.g. 0,1,2,3,3,3,4,5,6,6,6,7,8,9,...) Couldn't understand. Plz enlighten me :) Thanks.

    Read the article

  • When using SendKeys()-InvalidOperationException: Undo Operation encountered...

    - by M0DC0M
    Here is my code public void KeyPress() { //Finds the target window and sends a key command to the application Process[] processes = Process.GetProcessesByName("calc"); IntPtr calculatorHandle; foreach (Process proc in processes) { calculatorHandle = proc.MainWindowHandle; if (calculatorHandle == IntPtr.Zero) { MessageBox.Show("Calculator is not running."); return; } SetForegroundWindow(calculatorHandle); break; } SendKeys.SendWait("1"); } After Executing this code I recieve an Error, i know the source is the SendKeys. Here is the full error I am Receiving System.InvalidOperationException was unhandled Message="The Undo operation encountered a context that is different from what was applied in the corresponding Set operation. The possible cause is that a context was Set on the thread and not reverted(undone)." Source="mscorlib" StackTrace: at System.Threading.SynchronizationContextSwitcher.Undo() at System.Threading.ExecutionContextSwitcher.Undo() at System.Threading.ExecutionContext.runFinallyCode(Object userData, Boolean exceptionThrown) at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteBackoutCodeHelper(Object backoutCode, Object userData, Boolean exceptionThrown) at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Net.ContextAwareResult.Complete(IntPtr userToken) at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken) at System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped) at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP) InnerException: I'm not sure what the problem is, The number will appear in my calculator but that error pops up

    Read the article

  • Global Hotkey in Mono and Gtk#

    - by Zach Johnson
    I'm trying to get a global hotkey working in Linux using Mono. I found the signatures of XGrabKey and XUngrabKey, but I can't seem to get them working. Whenever I try to invoke XGrabKey, the application crashes with a SIGSEGV. This is what I have so far: using System; using Gtk; using System.Runtime.InteropServices; namespace GTKTest { class MainClass { const int GrabModeAsync = 1; public static void Main(string[] args) { Application.Init(); MainWindow win = new MainWindow(); win.Show(); // Crashes here XGrabKey( win.Display.Handle, (int)Gdk.Key.A, (uint)KeyMasks.ShiftMask, win.Handle, true, GrabModeAsync, GrabModeAsync); Application.Run(); XUngrabKey( win.Display.Handle, (int)Gdk.Key.A, (uint)KeyMasks.ShiftMask, win.Handle); } [DllImport("libX11")] internal static extern int XGrabKey( IntPtr display, int keycode, uint modifiers, IntPtr grab_window, bool owner_events, int pointer_mode, int keyboard_mode); [DllImport("libX11")] internal static extern int XUngrabKey( IntPtr display, int keycode, uint modifiers, IntPtr grab_window); } public enum KeyMasks { ShiftMask = (1 << 0), LockMask = (1 << 1), ControlMask = (1 << 2), Mod1Mask = (1 << 3), Mod2Mask = (1 << 4), Mod3Mask = (1 << 5), Mod4Mask = (1 << 6), Mod5Mask = (1 << 7) } } Does anyone have a working example of XGrabKey? Thanks!

    Read the article

  • Problems with native Win32api RichEdit control and its IRichEditOle interface

    - by Michael
    Hi All! As part of writing custom command (dll with class that implements Interwoven command interface) for one of Interwoven Worksite dialog boxes,I need to extract information from RichEdit textbox. The only connection to the existing dialog box is its HWND handle; Seemingly trivial task , but I got stuck : Using standard win32 api functions (like GetDlgItemText) returns empty string. After using Spy++ I noticed that the dialog box gets IRichEditOle interface and seems to encapsulate the string into OLE object. Here is what I tried to do: IRichEditOle richEditOleObj = null; IntPtr ppv = IntPtr.Zero; Guid guid = new Guid("00020D00-0000-0000-c000-000000000046"); Marshal.QueryInterface(pRichEdit, ref guid, out ppv); richEditOleObj = (IRichEditOle)Marshal.GetTypedObjectForIUnknown(ppv,typeof(IRichEditOle)); judging by GetObjectCount() method of the interface there is exactly one object in the textbox - most likely the string I need to extract. I used GetObject() method and got IOleObject interface via QueryInterface : if (richEditOleObj.GetObject(0, reObject, GetObjectOptions.REO_GETOBJ_ALL_INTERFACES) == 0) //S_OK { IntPtr oleObjPpv = IntPtr.Zero; try { IOleObject oleObject = null; Guid objGuid = new Guid("00000112-0000-0000-C000-000000000046"); Marshal.QueryInterface(reObject.poleobj, ref objGuid, out oleObjPpv); oleObject = (IOleObject)Marshal.GetTypedObjectForIUnknown(oleObjPpv, typeof(IOleObject)); To negate other possibilites I tried to QueryInteface IRichEditOle to ITextDocument but this also returned empty string; tried to send EM_STREAMOUT message and read buffer returned from callback - returned empty buffer. And on this point I got stuck. Googling didn't help much - couldn't find anything that was relevant to my issue - it seems that vast majority of examples on the net about IRichEditOle and RichEdit revolve around inserting bitmap into RichEdit control... Now since I know only basic stuff about COM and OLE , I guess I am missing something important here. I would appreciate any thoughts suggestions or remarks.

    Read the article

  • Calling unmanaged dll from C#. Take 2

    - by Charles Gargent
    I have written a c# program that calls a c++ dll that echoes the commandline args to a file When the c++ is called using the rundll32 command it displays the commandline args no problem, however when it is called from within the c# it doesnt. I asked this question to try and solve my problem, but I have modified it my test environment and I think it is worth asking a new question. Here is the c++ dll #include "stdafx.h" #include "stdlib.h" #include <stdio.h> #include <iostream> #include <fstream> using namespace std; BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { return TRUE; } extern "C" __declspec(dllexport) int WINAPI CMAKEX( HWND hwnd, HINSTANCE hinst, LPCSTR lpszCommandLine, DWORD dwReserved) { ofstream SaveFile("output.txt"); SaveFile << lpszCommandLine; SaveFile.close(); return 0; } Here is the c# app using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.Runtime.InteropServices; using System.Net; namespace nac { class Program { [DllImport("cmakca.dll", SetLastError = true, CharSet = CharSet.Unicode)] static extern bool CMAKEX(IntPtr hwnd, IntPtr hinst, string lpszCmdLine, int nCmdShow); static void Main(string[] args) { string cmdLine = @"/source_filename proxy-1.txt /backup_filename proxy.bak /DialRasEntry NULL /TunnelRasEntry DSLVPN /profile ""C:\Documents and Settings\Administrator\Application Data\Microsoft\Network\Connections\Cm\dslvpn.cmp"""; const int SW_SHOWNORMAL = 1; CMAKEX(IntPtr.Zero, IntPtr.Zero, cmdLine, SW_SHOWNORMAL).ToString(); } } } The output from the rundll32 command is rundll32 cmakex.dll,CMAKEX /source_filename proxy-1.txt /backup_filename proxy.bak /DialRasEntry NULL /TunnelRasEntry DSLVPN /profile ""C:\Documents and Settings\Administrator\Application Data\Microsoft\Network\Connections\Cm\dslvpn.cmp" /source_filename proxy-1.txt /backup_filename proxy.bak /DialRasEntry NULL /TunnelRasEntry DSLVPN /profile ""C:\Documents and Settings\Administrator\Application Data\Microsoft\Network\Connections\Cm\dslvpn.cmp" however the output when the c# app runs is /

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >