Search Results

Search found 296 results on 12 pages for 'marshal'.

Page 10/12 | < Previous Page | 6 7 8 9 10 11 12  | Next Page >

  • SendInput scan code on Windows 7 x64

    - by Stanomatic
    I am working with a WPF application sending keys to a game. I opened spy++ to observer s as a key press on the keyboard. I then press my button on the application and I noticed a different scan code in spy++ messages. Could this be somthing to do with Windows 7 64bit? Partial listing: var down = new INPUT(); down.Type = (UInt32)InputType.KEYBOARD; down.Data.Keyboard = new KEYBDINPUT(); down.Data.Keyboard.Vk = (UInt16)keyCode; down.Data.Keyboard.Scan = 0; down.Data.Keyboard.Flags = 0; down.Data.Keyboard.Time = 0; down.Data.Keyboard.ExtraInfo = IntPtr.Zero; //down.Data.Keyboard.ExtraInfo = GetMessageExtraInfo(); var up = new INPUT(); up.Type = (UInt32)InputType.KEYBOARD; up.Data.Keyboard = new KEYBDINPUT(); up.Data.Keyboard.Vk = (UInt16)keyCode; up.Data.Keyboard.Scan = 0; up.Data.Keyboard.Flags = (UInt32)KeyboardFlag.KEYUP; up.Data.Keyboard.Time = 0; up.Data.Keyboard.ExtraInfo = IntPtr.Zero; //up.Data.Keyboard.ExtraInfo = GetMessageExtraInfo(); INPUT[] inputList = new INPUT[2]; inputList[0] = down; inputList[1] = up; var numberOfSuccessfulSimulatedInputs = SendInput(2, inputList, Marshal.SizeOf(typeof(INPUT))); The image shows when I use my code to send a key I receive ScanCode:00fExtended from spy++ message output. When I actually press the same key I receive ScanCode:1FfExtended. Everything else is identical.

    Read the article

  • Misalignement in the output Bitmap created from a byte array

    - by Daniel
    I am trying to understand why I have troubles creating a Bitmap from a byte array. I post this after a careful scrutiny of the existing posts about Bitmap creation from byte arrays, like the followings: Creating a bitmap from a byte[], Working with Image and Bitmap in c#?, C#: Bitmap Creation using bytes array My code is aimed to execute a filter on a digital image 8bppIndexed writing the pixel value on a byte [] buffer to be converted again (after some processing to manage gray levels) in a 8BppIndexed Bitmap My input image is a trivial image created by means of specific perl code: https://www.box.com/shared/zqt46c4pcvmxhc92i7ct Of course, after executing the filter the output image has lost the first and last rows and the first and last columns, due to the way the filter manage borders, so from the original 256 x 256 image i get a 254 x 254 image. Just to stay focused on the issue I have commented the code responsible for executing the filter so that the operation really performed is an obvious: ComputedPixel = InputImage.GetPixel(myColumn, myRow).R; I know, i should use lock and unlock but I prefer one headache one by one. Anyway this code should be a sort of identity transform, and at last i use: private unsafe void FillOutputImage() { OutputImage = new Bitmap (OutputImageCols, OutputImageRows , PixelFormat .Format8bppIndexed); ColorPalette ncp = OutputImage.Palette; for (int i = 0; i < 256; i++) ncp.Entries[i] = Color .FromArgb(255, i, i, i); OutputImage.Palette = ncp; Rectangle area = new Rectangle(0, 0, OutputImageCols, OutputImageRows); var data = OutputImage.LockBits(area, ImageLockMode.WriteOnly, OutputImage.PixelFormat); Marshal .Copy (byteBuffer, 0, data.Scan0, byteBuffer.Length); OutputImage.UnlockBits(data); } The output image I get is the following: https://www.box.com/shared/p6tubyi6dsf7cyregg9e It is quite clear that I am losing a pixel per row, but i cannot understand why: I have carefully controlled all the parameters: OutputImageCols, OutputImageRows and the byte [] byteBuffer length and content even writing known values as way to test. The code is nearly identical to other code posted in stackOverflow and elsewhere. Someone maybe could help to identify where the problem is? Thanks a lot

    Read the article

  • Heroku push rejected, failed to install gems via Bundler

    - by ismaelsow
    Hi everybody ! I am struggling to push my code to Heroku. And after searching on Google and Stack Overflow questions, I have not been able to find the solution. Here is What I get when I try "git push heroku master" : Heroku receiving push -----> Rails app detected -----> Detected Rails is not set to serve static_assets Installing rails3_serve_static_assets... done -----> Gemfile detected, running Bundler version 1.0.3 Unresolved dependencies detected; Installing... Fetching source index for http://rubygems.org/ /usr/ruby1.8.7/lib/ruby/site_ruby/1.8/rubygems/remote_fetcher.rb:300:in `open_uri_or_path': bad response Not Found 404 (http://rubygems.org/quick/Marshal.4.8/mail-2.2.6.001.gemspec.rz) (Gem::RemoteFetcher::FetchError) from /usr/ruby1.8.7/lib/ruby/site_ruby/1.8/rubygems/remote_fetcher.rb:172:in `fetch_path' . .... And finally: FAILED: http://docs.heroku.com/bundler ! Heroku push rejected, failed to install gems via Bundler error: hooks/pre-receive exited with error code 1 To [email protected]:myapp.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to '[email protected]:myapp.git' Thanks for your help!

    Read the article

  • Return a list of imported Python modules used in a script?

    - by Jono Bacon
    Hi All, I am writing a program that categorizes a list of Python files by which modules they import. As such I need to scan the collection of .py files ad return a list of which modules they import. As an example, if one of the files I import has the following lines: import os import sys, gtk I would like it to return: ["os", "sys", "gtk"] I played with modulefinder and wrote: from modulefinder import ModuleFinder finder = ModuleFinder() finder.run_script('testscript.py') print 'Loaded modules:' for name, mod in finder.modules.iteritems(): print '%s ' % name, but this returns more than just the modules used in the script. As an example in a script which merely has: import os print os.getenv('USERNAME') The modules returned from the ModuleFinder script return: tokenize heapq __future__ copy_reg sre_compile _collections cStringIO _sre functools random cPickle __builtin__ subprocess cmd gc __main__ operator array select _heapq _threading_local abc _bisect posixpath _random os2emxpath tempfile errno pprint binascii token sre_constants re _abcoll collections ntpath threading opcode _struct _warnings math shlex fcntl genericpath stat string warnings UserDict inspect repr struct sys pwd imp getopt readline copy bdb types strop _functools keyword thread StringIO bisect pickle signal traceback difflib marshal linecache itertools dummy_thread posix doctest unittest time sre_parse os pdb dis ...whereas I just want it to return 'os', as that was the module used in the script. Can anyone help me achieve this?

    Read the article

  • Return a list of important Python modules in a script?

    - by Jono Bacon
    Hi All, I am writing a program that categorizes a list of Python files by which modules they import. As such I need to scan the collection of .py files ad return a list of which modules they import. As an example, if one of the files I import has the following lines: import os import sys, gtk I would like it to return: ["os", "sys", "gtk"] I played with modulefinder and wrote: from modulefinder import ModuleFinder finder = ModuleFinder() finder.run_script('testscript.py') print 'Loaded modules:' for name, mod in finder.modules.iteritems(): print '%s ' % name, but this returns more than just the modules used in the script. As an example in a script which merely has: import os print os.getenv('USERNAME') The modules returned from the ModuleFinder script return: tokenize heapq __future__ copy_reg sre_compile _collections cStringIO _sre functools random cPickle __builtin__ subprocess cmd gc __main__ operator array select _heapq _threading_local abc _bisect posixpath _random os2emxpath tempfile errno pprint binascii token sre_constants re _abcoll collections ntpath threading opcode _struct _warnings math shlex fcntl genericpath stat string warnings UserDict inspect repr struct sys pwd imp getopt readline copy bdb types strop _functools keyword thread StringIO bisect pickle signal traceback difflib marshal linecache itertools dummy_thread posix doctest unittest time sre_parse os pdb dis ...whereas I just want it to return 'os', as that was the module used in the script. Can anyone help me achieve this?

    Read the article

  • Check if file is locked or catch error for trying to open

    - by Duncan Matheson
    I'm trying to handle the problem where a user can try to open, with an OpenFileDialog, a file that is open by Excel. Using the simple FileInfo.OpenRead(), it chucks an IOException, "The process cannot access the file 'cakes.xls' because it is being used by another process." This would be fine to display to the user except that the user will actually get "Debugging resource strings are unavailable" nonsense. It seems not possible to open a file that is open by another process, since using FileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite) chucks a SecurityException, "File operation not permitted. Access to path 'C:\whatever\cakes.xls' is denied.", for any file. Rather unhelpful. So it's down to either finding some way of checking if the file is locked, or trying to catch the IOException. I don't want to catch all IOExceptions and assume they're all locked file errors, so I need some sort of way of classifying this type of exception as this error... but the "Debugging resource strings" nonsense along with the fact that that message itself is probably localized makes it tricky. I'm partial trust, so I can't use Marshal.GetHRForException. So: Is there any sensible way of either check if a file is locked, or at least determining if this problem occurred without just catching all IOExceptions?

    Read the article

  • FindWindowEx from user32.dll is returning a handle of Zero and error code of 127 using dllimport

    - by puretechy
    I need to handle another windows application programatically, searching google I found a sample which handles windows calculator using DLLImport Attribute and importing the user32.dll functions into managed ones in C#. The application is running, I am getting the handle for the main window i.e. Calculator itself, but the afterwards code is not working. The FindWindowEx method is not returning the handles of the children of the Calculator like buttons and textbox. I have tried using the SetLastError=True on DLLImport and found that I am getting an error code of 127 which is "Procedure not found". This is the link from where I got sample application: http://www.codeproject.com/script/Articles/ArticleVersion.aspx?aid=14519&av=34503 Please help if anyone knows how to solve it. UPDATE: The DLLImport is: [DllImport("user32.dll", SetLastError = true)] public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle); The Code that is not working is: hwnd=FindWindow(null,"Calculator"); // This is working, I am getting handle of Calculator // The following is not working, I am getting hwndChild=0 and err = 127 hwndChild = FindWindowEx((IntPtr)hwnd,IntPtr.Zero,"Button","1"); Int32 err = Marshal.GetLastWin32Error();

    Read the article

  • Reference a GNU C DLL built in GCC against Cygwin, from C#/NET

    - by Dale Halliwell
    Here is what I want: I have a huge legacy C/C++ codebase written for POSIX, including some very POSIX specific stuff like pthreads. This can be compiled on Cygwin/GCC and run as an executable under Windows with the Cygwin DLL. What I would like to do is build the codebase itself into a Windows DLL that I can then reference from C# and write a wrapper around it to access some parts of it programatically. I have tried this approach with the very simple "hello world" example at http://www.cygwin.com/cygwin-ug-net/dll.html and it doesn't seem to work. #include <stdio.h> extern "C" __declspec(dllexport) int hello(); int hello() { printf ("Hello World!\n"); return 42; } I believe I should be able to reference a DLL built with the above code in C# using something like: [DllImport("kernel32.dll")] public static extern IntPtr LoadLibrary(string dllToLoad); [DllImport("kernel32.dll")] public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName); [DllImport("kernel32.dll")] public static extern bool FreeLibrary(IntPtr hModule); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int hello(); static void Main(string[] args) { var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "helloworld.dll"); IntPtr pDll = LoadLibrary(path); IntPtr pAddressOfFunctionToCall = GetProcAddress(pDll, "hello"); hello hello = (hello)Marshal.GetDelegateForFunctionPointer( pAddressOfFunctionToCall, typeof(hello)); int theResult = hello(); Console.WriteLine(theResult.ToString()); bool result = FreeLibrary(pDll); Console.ReadKey(); } But this approach doesn't seem to work. LoadLibrary returns null. It can find the DLL (helloworld.dll), it is just like it can't load it or find the exported function. I am sure that if I get this basic case working I can reference the rest of my codebase in this way. Any suggestions or pointers, or does anyone know if what I want is even possible? Thanks.

    Read the article

  • C# to unmanaged dll data structures interop

    - by Shane Powell
    I have a unmanaged DLL that exposes a function that takes a pointer to a data structure. I have C# code that creates the data structure and calls the dll function without any problem. At the point of the function call to the dll the pointer is correct. My problem is that the DLL keeps the pointer to the structure and uses the data structure pointer at a later point in time. When the DLL comes to use the pointer it has become invalid (I assume the .net runtime has moved the memory somewhere else). What are the possible solutions to this problem? The possible solutions I can think of are: Fix the memory location of the data structure somehow? I don't know how you would do this in C# or even if you can. Allocate memory manually so that I have control over it e.g. using Marshal.AllocHGlobal Change the DLL function contract to copy the structure data (this is what I'm currently doing as a short term change, but I don't want to change the dll at all if I can help it as it's not my code to begin with). Are there any other better solutions?

    Read the article

  • .NET framework execution aborted while executing CLR stored procedure?

    - by Sean Ochoa
    I constructed a stored procedure that does the equivalent of FOR XML AUTO in SQL Server 2008. Now that I'm testing it, it gives me a really unhelpful error message. What does this error mean? Msg 10329, Level 16, State 49, Procedure ForXML, Line 0 .NET Framework execution was aborted. System.Threading.ThreadAbortException: Thread was being aborted. System.Threading.ThreadAbortException: at System.Runtime.InteropServices.Marshal.PtrToStringUni(IntPtr ptr, Int32 len) at System.Data.SqlServer.Internal.CXVariantBase.WSTRToString() at System.Data.SqlServer.Internal.SqlWSTRLimitedBuffer.GetString(SmiEventSink sink) at System.Data.SqlServer.Internal.RowData.GetString(SmiEventSink sink, Int32 i) at Microsoft.SqlServer.Server.ValueUtilsSmi.GetValue(SmiEventSink_Default sink, ITypedGettersV3 getters, Int32 ordinal, SmiMetaData metaData, SmiContext context) at Microsoft.SqlServer.Server.ValueUtilsSmi.GetValue200(SmiEventSink_Default sink, SmiTypedGetterSetter getters, Int32 ordinal, SmiMetaData metaData, SmiContext context) at System.Data.SqlClient.SqlDataReaderSmi.GetValue(Int32 ordinal) at System.Data.SqlClient.SqlDataReaderSmi.GetValues(Object[] values) at System.Data.ProviderBase.DataReaderContainer.CommonLanguageSubsetDataReader.GetValues(Object[] values) at System.Data.ProviderBase.SchemaMapping.LoadDataRow() at System.Data.Common.DataAdapter.FillLoadDataRow(SchemaMapping mapping) at System.Data.Common.DataAdapter.FillFromReader(DataSet dataset, DataTable datatable, String srcTable, DataReaderContainer dataReader, Int32 startRecord, Int32 maxRecords, DataColumn parentChapterColumn, Object parentChapterValue) at System.Data.Common.DataAdapter.Fill(DataTable[] dataTables, IDataReader dataReader, Int32 startRecord, Int32 maxRecords) at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior) at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable) at ForXML.GetXML...

    Read the article

  • Cocoa NSTextField Drag & Drop Requires Subclass... Really?

    - by ipmcc
    Until today, I've never had occasion to use anything other than an NSWindow itself as an NSDraggingDestination. When using a window as a one-size-fits-all drag destination, the NSWindow will pass those messages on to its delegate, allowing you to handle drops without subclassing NSWindow. The docs say: Although NSDraggingDestination is declared as an informal protocol, the NSWindow and NSView subclasses you create to adopt the protocol need only implement those methods that are pertinent. (The NSWindow and NSView classes provide private implementations for all of the methods.) Either a window object or its delegate may implement these methods; however, the delegate’s implementation takes precedence if there are implementations in both places. Today, I had a window with two NSTextFields on it, and I wanted them to have different drop behaviors, and I did not want to allow drops anywhere else in the window. The way I interpret the docs, it seems that I either have to subclass NSTextField, or make some giant spaghetti-conditional drop handlers on the window's delegate that hit-checks the draggingLocation against each view in order to select the different drop-area behaviors for each field. The centralized NSWindow-delegate-based drop handler approach seems like it would be onerous in any case where you had more than a small handful of drop destination views. Likewise, the subclassing approach seems onerous regardless of the case, because now the drop handling code lives in a view class, so once you accept the drop you've got to come up with some way to marshal the dropped data back to the model. The bindings docs warn you off of trying to drive bindings by setting the UI value programmatically. So now you're stuck working your way back around that too. So my question is: "Really!? Are those the only readily available options? Or am I missing something straightforward here?" Thanks.

    Read the article

  • XMLAdapter for HashMap

    - by denniss
    I want to convert a list of items inside of my payaload and convert them into a hashmap. Basically, what I have is an Item xml representation which have a list of ItemID. Each ItemID has an idType in it. However, inside my Item class, i want these ItemIDs to be represented as a Map. HashMap<ItemIDType, ItemID> The incoming payload will represent this as a list <Item>... <ItemIDs> <ItemID type="external" id="XYZ"/> <ItemID type="internal" id="20011"/> </ItemIDs> </Item> but I want an adapter that will convert this into a HashMap "external" => "xyz" "internal" => "20011" I am right now using a LinkedList public class MapHashMapListAdapter extends XmlAdapter<LinkedList<ItemID>, Map<ItemIDType, ItemID>> { public LinkedList<ItemID> marshal(final Map<ItemIDType, ItemID> v) throws Exception { ... } public Map<ItemIDType, ItemID> unmarshal(final LinkedList<ItemID> v) throws Exception { ... } } but for some reason when my payload gets converted, it fails to convert the list into a hashmap. The incoming LinkedList of the method unmarshal is an empty list. Do you guys have any idea what I am doing wrong here? Do I need to create my own data type here to handle the LinkedList?

    Read the article

  • Getting the full-name of the current user, returns an empty string (C#/C++)

    - by Nir
    I try to get the full-name of the current log-in user (Fullname, not username). The following code C#, C++ works fine but on XP computers not connected to the Net, I get empty string as result if I run it ~20 minutes after login (It runs OK whithin the first ~20 minutes after login) A Win32 API (GetUserNameEx) is used rather that PrincipalContext since it PrincipalContext may takes up to 15 seconds when working offline. Any Help why am I getting an empty string as result though a user full name is specified??? - C# Code public static string CurrentUserFullName { get { const int EXTENDED_NAME_FORMAT_NAME_DISPLAY = 3; StringBuilder userName = new StringBuilder(256); uint length = (uint) userName.Capacity; string ret; if (GetUserNameEx(EXTENDED_NAME_FORMAT_NAME_DISPLAY, userName, ref length)) { ret = userName.ToString(); } else { int errorCode = Marshal.GetLastWin32Error(); throw new Win32Exception("GetUserNameEx Failed. Error code - " + errorCode); } return ret; } } [DllImport("Secur32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern bool GetUserNameEx(int nameFormat, StringBuilder lpNameBuffer, ref uint lpnSize); - Code in C++ #include "stdafx.h" #include <windows.h> #define SECURITY_WIN32 #include <Security.h> #pragma comment( lib, "Secur32.lib" ) int _tmain(int argc, _TCHAR* argv[]) { char szName[100]; ULONG nChars = sizeof( szName ); if ( GetUserNameEx( NameDisplay, szName, &nChars ) ) { printf( "Name: %s\n", szName); } else { printf( "Failed to GetUserNameEx\n" ); printf( "%d\n", GetLastError() ); } return 0; }

    Read the article

  • Extra NotifyIcon shown in system tray

    - by Kettch19
    I'm having an issue with an app where my NotifyIcon displays an extra icon. The steps to reproduce it are easy, but the problem is that the extra icon shows up after any of the actual codebehind we've added fires. Put simply, clicking a button triggers execution of method FooBar() which runs all the way through fine but its primary duty is to fire a backgroundworker to log into another of our apps. It only appears if this particular button is clicked. Strangely enough, we have a WndProc method override and if I step through until the extra NotifyIcon appears, it always appears during this method so something else beyond the codebehind must be triggering the behavior. Our WndProc method is currently (although I don't think it's caused by the WndProc): Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message) 'Check for WM_COPYDATA message from other app or drag/drop action and handle message If m.Msg = NativeMethods.WM_COPYDATA Then ' get the standard message structure from lparam Dim CD As NativeMethods.COPYDATASTRUCT = m.GetLParam(GetType(NativeMethods.COPYDATASTRUCT)) 'setup byte array Dim B(CD.cbData) As Byte 'copy data from memory into array Runtime.InteropServices.Marshal.Copy(New IntPtr(CD.lpData), B, 0, CD.cbData) 'Get message as string and process ProcessWMCopyData(System.Text.Encoding.Default.GetString(B)) 'empty array Erase B 'set message result to 'true', meaning message handled m.Result = New IntPtr(1) End If 'pass on result and all messages not handled by this app MyBase.WndProc(m) End Sub The only place in the code where the NotifyIcon in question is manipulated at all is in the following event handler (again, don't think this is the culprit, but just for more info): Private Sub TrayIcon_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles TrayIcon.MouseDoubleClick If Me.Visible Then Me.Hide() Else PositionBottomRight() Me.Show() End If End Sub The backgroundworker's DoWork is as follows (just a class call to log in to our other app, but again just for info): Private Sub LoginBackgroundWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles LoginBackgroundWorker.DoWork Settings.IsLoggedIn = _wdService.LogOn(Settings.UserName, Settings.Password) End Sub Does anyone else have ideas on what might be causing this or how to possibly further debug this? I've been banging my head on this without seeing a pattern so another set of eyes would be extremely appreciated. :) I've posted this on MSDN winforms forums as well and have had no luck there so far either.

    Read the article

  • finding the maximum in series

    - by peril brain
    I need to know a code that will automatically:- search a specific word in excel notes it row or column number (depends on data arrangement) searches numerical type values in the respective row or column with that numeric value(suppose a[7][0]or a[0][7]) it compares all other values of respective row or column(ie. a[i][0] or a[0][i]) sets that value to the highest value only if IT HAS GOT NO FORMULA FOR DERIVATION i know most of coding but at a few places i got myself stuck... i'm writing a part of my program upto which i know: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading; using Microsoft.Office.Interop; using Excel = Microsoft.Office.Interop.Excel; Excel.Application oExcelApp; namespace a{ class b{ static void main(){ try { oExcelApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application"); ; if(oExcelApp.ActiveWorkbook != null) {Excel.Workbook xlwkbook = (Excel.Workbook)oExcelApp.ActiveWorkbook; Excel.Worksheet ws = (Excel.Worksheet)xlwkbook.ActiveSheet; Excel.Range rn; rn = ws.Cells.Find("maximum", Type.Missing, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart,Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false, Type.Missing, Type.Missing); }}} now ahead of this i only know tat i have to use cell.value2 ,cell.hasformula methods..... & no more idea can any one help me with this..

    Read the article

  • How do I handle freeing unmanaged structures on application close?

    - by LostKaleb
    I have a C# project in which i use several unmanaged C++ functions. More so, I also have static IntPtr that I use as parameters for those functions. I know that whenever I use them, I should implement IDisposable in that class and use a destructor to invoke the Dispose method, where I free the used IntPtr, as is said in the MSDN page. public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!this.disposed) { if (disposing) { component.Dispose(); } CloseHandle(m_InstanceHandle); m_InstanceHandle = IntPtr.Zero; disposed = true; } } [System.Runtime.InteropServices.DllImport("Kernel32")] private extern static Boolean CloseHandle(IntPtr handle); However, when I terminate the application, I'm still left with a hanging process in TaskManager. I believe that it must be related to the used of the MarshalAs instruction in my structures: [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct SipxAudioCodec { [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string CodecName; public SipxAudioBandwidth Bandwidth; public int PayloadType; } When I create such a structure should I also be careful to free the space it allocs using a destructor? [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct SipxAudioCodec { [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string CodecName; public SipxAudioBandwidth Bandwidth; public int PayloadType; ~SipxAudioCodec() { Marshal.FreeGlobal(something...); } }

    Read the article

  • Exposing a C++ API to C#

    - by Siyfion
    So what I have is a C++ API contained within a *.dll and I want to use a C# application to call methods within the API. So far I have created a C++ / CLR project that includes the native C++ API and managed to create a "bridge" class that looks a bit like the following: ManagedBridge.h namespace ManagedAPIWrapper { public ref class Bridge { public: int bridge_test(void); int bridge_test2(api_struct* temp); } } ManagedBridge.cpp int Bridge::bridge_test(void) { return test(); } int Bridge::bridge_test2(api_struct* temp) { return test2(temp); } I also have a C# application that has a reference to the C++/CLR "Bridge.dll" and then uses the methods contained within. I have a number of problems with this: I can't figure out how to call bridge_test2 within the C# program, as it has no knowledge of what a api_struct actually is. I know that I need to marshal the object somewhere, but do I do it in the C# program or the C++/CLR bridge? This seems like a very long-winded way of exposing all of the methods in the API, is there not an easier way that I'm missing out? (That doesn't use P/Invoke!)

    Read the article

  • search for the maximum

    - by peril brain
    I need to know a code that will automatically:- search a specific word in excel notes it row or column number (depends on data arrangement) searches numerical type values in the respective row or column with that numeric value(suppose a[7][0]or a[0][7]) it compares all other values of respective row or column(ie. a[i][0] or a[0][i]) sets that value to the highest value only if IT HAS GOT NO FORMULA FOR DERIVATION i know most of coding but at a few places i got myself stuck... i'm writing a part of my program upto which i know: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading; using Microsoft.Office.Interop; using Excel = Microsoft.Office.Interop.Excel; Excel.Application oExcelApp; namespace a{ class b{ static void main(){ try { oExcelApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application"); ; if(oExcelApp.ActiveWorkbook != null) {Excel.Workbook xlwkbook = (Excel.Workbook)oExcelApp.ActiveWorkbook; Excel.Worksheet ws = (Excel.Worksheet)xlwkbook.ActiveSheet; Excel.Range rn; rn = ws.Cells.Find("maximum", Type.Missing, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart,Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false, Type.Missing, Type.Missing); }}} now ahead of this i only know tat i have to use cell.value2 ,cell.hasformula methods..... & no more idea can any one help me with this..

    Read the article

  • finding the maximum in the range

    - by comfreak
    I need to know a code that will automatically:- search a specific word in excel notes it row or column number (depends on data arrangement) searches numerical type values in the respective row or column with that numeric value(suppose a[7][0]or a[0][7]) it compares all other values of respective row or column(ie. a[i][0] or a[0][i]) sets that value to the highest value only if IT HAS GOT NO FORMULA FOR DERIVATION i know most of coding but at a few places i got myself stuck... i'm writing a part of my program upto which i know: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading; using Microsoft.Office.Interop; using Excel = Microsoft.Office.Interop.Excel; Excel.Application oExcelApp; namespace a{ class b{ static void main(){ try { oExcelApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application"); ; if(oExcelApp.ActiveWorkbook != null) {Excel.Workbook xlwkbook = (Excel.Workbook)oExcelApp.ActiveWorkbook; Excel.Worksheet ws = (Excel.Worksheet)xlwkbook.ActiveSheet; Excel.Range rn; rn = ws.Cells.Find("maximum", Type.Missing, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart,Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false, Type.Missing, Type.Missing); }}} now ahead of this i only know tat i have to use cell.value2 ,cell.hasformula methods..... & no more idea can any one help me with this..

    Read the article

  • Is there a Form.Invoke() method?

    - by rubicon
    Hi, I am new to multithreading (and also to C#) so I hope this is not obvious: In my Form (WinForms application, .NET 2.0) I subscribed to an event that is raised by another object, and on handling this event I wish to change several Controls on my Form. As this event is raised in another thread than the main (UI) thread I want to marshal the call to the Form's thread. I understand I could use the Control.Invoke() method on any Control that I want to change, but as there are several of them I do not wish to do that. When searching the internet I found hints that the Form class itself provides an Invoke() method. See for example: http://marioschneider.blogspot.com/2008/04/invoke-methode-fr-multithread.html (Sorry, as I am I new user I can't seem to post more than one link. I will add more links as comments if possible.) With that, I could just wrap my event handler and then use it as if it was called on the UI thread. However, this doesn't seem to be defined in my environment, and in MSDN's System.Windows.Forms.Form documentation there's also no sign of it. Does this method exist in the .NET-Framework? I find it hard to believe that Form would not supply such a method, as it uses the same message queue the Controls on it do. (Or am I missing something here?)

    Read the article

  • How do I handle freeing unmanaged structures in C# on application close?

    - by LostKaleb
    I have a C# project in which i use several unmanaged C++ functions. More so, I also have static IntPtr that I use as parameters for those functions. I know that whenever I use them, I should implement IDisposable in that class and use a destructor to invoke the Dispose method, where I free the used IntPtr, as is said in the MSDN page. public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!this.disposed) { if (disposing) { component.Dispose(); } CloseHandle(m_InstanceHandle); m_InstanceHandle = IntPtr.Zero; disposed = true; } } [System.Runtime.InteropServices.DllImport("Kernel32")] private extern static Boolean CloseHandle(IntPtr handle); However, when I terminate the application, I'm still left with a hanging process in TaskManager. I believe that it must be related to the used of the MarshalAs instruction in my structures: [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct SipxAudioCodec { [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string CodecName; public SipxAudioBandwidth Bandwidth; public int PayloadType; } When I create such a structure should I also be careful to free the space it allocs using a destructor? [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct SipxAudioCodec { [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string CodecName; public SipxAudioBandwidth Bandwidth; public int PayloadType; ~SipxAudioCodec() { Marshal.FreeGlobal(something...); } } Thanks in advance!

    Read the article

  • How to customize file dialog in wpf

    - by ManjuAnoop
    In Windows7 I am using a customized Open File Dialog( WPF application). My Open File dialog is derived from Microsoft.Win32.CommonDialog. The dialog have old look, how to change this to new look (windows7 file dialog look(Explorer style)). Code portion: private const int OFN_ENABLESIZING = 0x00800000; private const int OFN_EXPLORER = 0x00080000; private const int OFN_ENABLEHOOK = 0x00000020; protected override bool RunDialog(IntPtr hwndOwner) { OPENFILENAME_I.WndProc proc = new OPENFILENAME_I.WndProc(this.HookProc); OPENFILENAME_I ofn = new OPENFILENAME_I(); this._charBuffer = CharBuffer.CreateBuffer(0x2000); if (this._fileNames != null) { this._charBuffer.PutString(this._fileNames[0]); } ofn.lStructSize = Marshal.SizeOf(typeof(OPENFILENAME_I)); ofn.hwndOwner = hwndOwner; ofn.hInstance = IntPtr.Zero; ofn.lpstrFilter = MakeFilterString(this._filter, this.DereferenceLinks); ofn.nFilterIndex = this._filterIndex; ofn.lpstrFile = this._charBuffer.AllocCoTaskMem(); ofn.nMaxFile = this._charBuffer.Length; ofn.lpstrInitialDir = this._initialDirectory; ofn.lpstrTitle = this._title; ofn.Flags = OFN_EXPLORER | OFN_ENABLESIZING | OFN_ENABLEHOOK; ofn.lpfnHook = proc; ofn.FlagsEx = 0x1000000 ; NativeMethods.GetOpenFileName(ofn); // } [SecurityCritical, SuppressUnmanagedCodeSecurity, DllImport("comdlg32.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern bool GetOpenFileName([In, Out] OPENFILENAME_I ofn);

    Read the article

  • .net remoting - Better solution to wait for a service to initialize ?

    - by CitizenInsane
    Context I have a client application (which i cannot modify, i.e. i only have the binary) that needs to run from time to time external commands that depends on a resource which is very long to initialize (about 20s). I thus decided to initialize this resource once for all in a "CommandServer.exe" application (single instance in the system tray) and let my client application call an intermediate "ExecuteCommand.exe" program that uses .net remoting to perform the operation on the server. The "ExecuteCommand.exe" is in charge for starting the server on first call and then leave it alive to speed up further commands. The service: public interface IMyService { void ExecuteCommand(string[] args); } The "CommandServer.exe" (using WindowsFormsApplicationBase for single instance management + user friendly splash screen during resource initializations): private void onStartupFirstInstance(object sender, StartupEventArgs e) { // Register communication channel channel = new TcpServerChannel("CommandServerChannel", 8234); ChannelServices.RegisterChannel(channel, false); // Register service var resource = veryLongToInitialize(); service = new MyServiceImpl(resource); RemotingServices.Marshal(service, "CommandServer"); // Create icon in system tray notifyIcon = new NotifyIcon(); ... } The intermediate "ExecuteCommand.exe": static void Main(string[] args) { startCommandServerIfRequired(); var channel = new TcpClientChannel(); ChannelServices.RegisterChannel(channel, false); var service = (IMyService)Activator.GetObject(typeof(IMyService), "tcp://localhost:8234/CommandServer"); service.RunCommand(args); } Problem As the server is very long to start (about 20s to initialize the required resources), the "ExecuteCommand.exe" fails on service.RunCommand(args) line because the server is yet not available. Question Is there a elegant way I can tune the delay before to receive "service not available" when calling service.RunCommand ? NB1: Currently I'm working around the issue by adding a mutex in server to indicate for complete initiliazation and have "ExecuteCommand.exe" to wait for this mutex before to call service.RunCommand. NB2: I have no background with .net remoting, nor WCF which is recommended replacer. (I chose .net remoting because this looked easier to set-up for this single shot issue in running external commands).

    Read the article

  • Merging multiple docx files to one

    - by coding
    I am developing a desktop application in C#. I have coded a function to merge multiple docx files but it does not work as expected. I don't get the content exactly as how it was in the source files. A few blank lines are added in between. The content extends to the next pages, header and footer information is lost, page margins gets changed, etc.. How can I concatenate docs as it is without and change in it.Any suggestions will be helpful. This is my code. public bool CombineDocx(string[] filesToMerge, string destFilepath) { Application wordApp = null; Document wordDoc = null; object outputFile = destFilepath; object missing = Type.Missing; object pageBreak = WdBreakType.wdPageBreak; try { wordApp = new Application { DisplayAlerts = WdAlertLevel.wdAlertsNone, Visible = false }; wordDoc = wordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing); Selection selection = wordApp.Selection; foreach (string file in filesToMerge) { selection.InsertFile(file, ref missing, ref missing, ref missing, ref missing); selection.InsertBreak(ref pageBreak); } wordDoc.SaveAs( ref outputFile, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); return true; } catch (Exception ex) { Msg.Log(ex); return false; } finally { if (wordDoc != null) { wordDoc.Close(); } if (wordApp != null) { wordApp.DisplayAlerts = WdAlertLevel.wdAlertsAll; wordApp.Quit(); Marshal.FinalReleaseComObject(wordApp); } } }

    Read the article

  • C# 5 Async, Part 1: Simplifying Asynchrony – That for which we await

    - by Reed
    Today’s announcement at PDC of the future directions C# is taking excite me greatly.  The new Visual Studio Async CTP is amazing.  Asynchronous code – code which frustrates and demoralizes even the most advanced of developers, is taking a huge leap forward in terms of usability.  This is handled by building on the Task functionality in .NET 4, as well as the addition of two new keywords being added to the C# language: async and await. This core of the new asynchronous functionality is built upon three key features.  First is the Task functionality in .NET 4, and based on Task and Task<TResult>.  While Task was intended to be the primary means of asynchronous programming with .NET 4, the .NET Framework was still based mainly on the Asynchronous Pattern and the Event-based Asynchronous Pattern. The .NET Framework added functionality and guidance for wrapping existing APIs into a Task based API, but the framework itself didn’t really adopt Task or Task<TResult> in any meaningful way.  The CTP shows that, going forward, this is changing. One of the three key new features coming in C# is actually a .NET Framework feature.  Nearly every asynchronous API in the .NET Framework has been wrapped into a new, Task-based method calls.  In the CTP, this is done via as external assembly (AsyncCtpLibrary.dll) which uses Extension Methods to wrap the existing APIs.  However, going forward, this will be handled directly within the Framework.  This will have a unifying effect throughout the .NET Framework.  This is the first building block of the new features for asynchronous programming: Going forward, all asynchronous operations will work via a method that returns Task or Task<TResult> The second key feature is the new async contextual keyword being added to the language.  The async keyword is used to declare an asynchronous function, which is a method that either returns void, a Task, or a Task<T>. Inside the asynchronous function, there must be at least one await expression.  This is a new C# keyword (await) that is used to automatically take a series of statements and break it up to potentially use discontinuous evaluation.  This is done by using await on any expression that evaluates to a Task or Task<T>. For example, suppose we want to download a webpage as a string.  There is a new method added to WebClient: Task<string> WebClient.DownloadStringTaskAsync(Uri).  Since this returns a Task<string> we can use it within an asynchronous function.  Suppose, for example, that we wanted to do something similar to my asynchronous Task example – download a web page asynchronously and check to see if it supports XHTML 1.0, then report this into a TextBox.  This could be done like so: private async void button1_Click(object sender, RoutedEventArgs e) { string url = "http://reedcopsey.com"; string content = await new WebClient().DownloadStringTaskAsync(url); this.textBox1.Text = string.Format("Page {0} supports XHTML 1.0: {1}", url, content.Contains("XHTML 1.0")); } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Let’s walk through what’s happening here, step by step.  By adding the async contextual keyword to the method definition, we are able to use the await keyword on our WebClient.DownloadStringTaskAsync method call. When the user clicks this button, the new method (Task<string> WebClient.DownloadStringTaskAsync(string)) is called, which returns a Task<string>.  By adding the await keyword, the runtime will call this method that returns Task<string>, and execution will return to the caller at this point.  This means that our UI is not blocked while the webpage is downloaded.  Instead, the UI thread will “await” at this point, and let the WebClient do it’s thing asynchronously. When the WebClient finishes downloading the string, the user interface’s synchronization context will automatically be used to “pick up” where it left off, and the Task<string> returned from DownloadStringTaskAsync is automatically unwrapped and set into the content variable.  At this point, we can use that and set our text box content. There are a couple of key points here: Asynchronous functions are declared with the async keyword, and contain one or more await expressions In addition to the obvious benefits of shorter, simpler code – there are some subtle but tremendous benefits in this approach.  When the execution of this asynchronous function continues after the first await statement, the initial synchronization context is used to continue the execution of this function.  That means that we don’t have to explicitly marshal the call that sets textbox1.Text back to the UI thread – it’s handled automatically by the language and framework!  Exception handling around asynchronous method calls also just works. I’d recommend every C# developer take a look at the documentation on the new Asynchronous Programming for C# and Visual Basic page, download the Visual Studio Async CTP, and try it out.

    Read the article

< Previous Page | 6 7 8 9 10 11 12  | Next Page >