Search Results

Search found 543 results on 22 pages for 'extern'.

Page 9/22 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • Using C++ DLL in C# project

    - by Frank
    Hello, I got a C++ dll which has to be integrated in a C# project. I think I found the correct way to do it, but calling the dll gives me this error: System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) This is the function in the dll: extern long FAR PASCAL convert (LPSTR filename); And this is the code I'm using in C# namespace Test{ public partial class Form1 : Form { [DllImport("convert.dll", SetLastError = true)] static extern Int32 convert([MarshalAs(UnmanagedType.LPStr)] string filename); private void button1_Click(object sender, EventArgs e) { // generate textfile string filename = "testfile.txt"; StreamWriter sw = new StreamWriter(filename); sw.WriteLine("line1"); sw.WriteLine("line2"); sw.Close(); // add checksum Int32 ret = 0; try { ret = convert(filename); Console.WriteLine("Result of DLL: {0}", ret.ToString()); } catch (Exception ex) { lbl.Text = ex.ToString(); } } }} Any ideas on how to proceed with this? Thanks a lot, Frank

    Read the article

  • Send Click Message to another application process

    - by Nazar
    Hi Guys I have a scenario, i need to send click events to an independent application. I started that application with the following code. private Process app; app = new Process(); app.StartInfo.FileName = app_path; app.StartInfo.WorkingDirectory = dir_path; app.Start(); Now i want to send Mouse click message to that applicaiton, I have specific coordinates in relative to application window. How can i do it using Windows Messaging or any other technique. I used [DllImport("user32.dll")] private static extern void mouse_event(UInt32 dwFlags, UInt32 dx, UInt32 dy, UInt32 dwData, IntPtr dwExtraInfo); It works well but cause the pointer to move as well. So not fit for my need. Then i use. [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)] static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); It works well for minimize maximize, but do not work for mouse events. The codes for mousevents i am using are, WM_LBUTTONDOWN = 0x201, //Left mousebutton down WM_LBUTTONUP = 0x202, //Left mousebutton up WM_LBUTTONDBLCLK = 0x203, //Left mousebutton doubleclick WM_RBUTTONDOWN = 0x204, //Right mousebutton down WM_RBUTTONUP = 0x205, //Right mousebutton up WM_RBUTTONDBLCLK = 0x206, //Right mousebutton do Thanks for the help in advance, and waiting for feedback.

    Read the article

  • C++ Switch won't compile with externally defined variable used as case

    - by C Nielsen
    I'm writing C++ using the MinGW GNU compiler and the problem occurs when I try to use an externally defined integer variable as a case in a switch statement. I get the following compiler error: "case label does not reduce to an integer constant". Because I've defined the integer variable as extern I believe that it should compile, does anyone know what the problem may be? Below is an example: test.cpp #include <iostream> #include "x_def.h" int main() { std::cout << "Main Entered" << std::endl; switch(0) { case test_int: std::cout << "Case X" << std::endl; break; default: std::cout << "Case Default" << std::endl; break; } return 0; } x_def.h extern const int test_int; x_def.cpp const int test_int = 0; This code will compile correctly on Visual C++ 2008. Furthermore a Montanan friend of mine checked the ISO C++ standard and it appears that any const-integer expression should work. Is this possibly a compiler bug or have I missed something obvious? Here's my compiler version information: Reading specs from C:/MinGW/bin/../lib/gcc/mingw32/3.4.5/specs Configured with: ../gcc-3.4.5-20060117-3/configure --with-gcc --with-gnu-ld --with-gnu-as --host=mingw32 --target=mingw32 --prefix=/mingw --enable-threads --disable-nls --enable-languages=c,c++,f77,ada,objc,java --disable-win32-registry --disable-shared --enable-sjlj-exceptions --enable-libgcj --disable-java-awt --without-x --enable-java-gc=boehm --disable-libgcj-debug --enable-interpreter --enable-hash-synchronization --enable-libstdcxx-debug Thread model: win32 gcc version 3.4.5 (mingw-vista special r3)

    Read the article

  • Get an array of structures from native dll to c# application

    - by PaulH
    I have a C# .NET 2.0 CF project where I need to invoke a method in a native C++ DLL. This native method returns an array of type TableEntry. At the time the native method is called, I do not know how large the array will be. How can I get the table from the native DLL to the C# project? Below is effectively what I have now. // in C# .NET 2.0 CF project [StructLayout(LayoutKind.Sequential)] public struct TableEntry { [MarshalAs(UnmanagedType.LPWStr)] public string description; public int item; public int another_item; public IntPtr some_data; } [DllImport("MyDll.dll", CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Auto)] public static extern bool GetTable(ref TableEntry[] table); SomeFunction() { TableEntry[] table = null; bool success = GetTable( ref table ); // at this point, the table is empty } // In Native C++ DLL std::vector< TABLE_ENTRY > global_dll_table; extern "C" __declspec(dllexport) bool GetTable( TABLE_ENTRY* table ) { table = &global_dll_table.front(); return true; } Thanks, PaulH

    Read the article

  • C++: best way to implement globally scoped data

    - by bobobobo
    I'd like to make program-wide data in a C++ program, without running into pesky LNK2005 errors when all the source files #includes this "global variable repository" file. I have 2 ways to do it in C++, and I'm asking which way is better. The easiest way to do it in C# is just public static members. C#: public static class DataContainer { public static Object data1 ; public static Object data2 ; } In C++ you can do the same thing C++ global data way#1: class DataContainer { public: static Object data1 ; static Object data2 ; } ; Object DataContainer::data1 ; Object DataContainer::data2 ; However there's also extern C++ global data way #2: class DataContainer { public: Object data1 ; Object data2 ; } ; extern DataContainer * dataContainer ; // instantiate in .cpp file In C++ which is better, or possibly another way which I haven't thought about? The solution has to not cause LNK2005 "object already defined" errors.

    Read the article

  • How to get around DnsRecordListFree error in .NET Framework 4.0?

    - by Greg Finzer
    I am doing an MxRecordLookup. I am getting an error when calling the DnsRecordListFree in the .NET Framework 4.0. I am using Windows 7. How do I get around it? Here is the error: System.MethodAccessException: Attempt by security transparent method to call native code through method. Here is my code: [DllImport("dnsapi", EntryPoint = "DnsQuery_W", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)] private static extern int DnsQuery([MarshalAs(UnmanagedType.VBByRefStr)]ref string pszName, QueryTypes wType, QueryOptions options, int aipServers, ref IntPtr ppQueryResults, int pReserved); [DllImport("dnsapi", CharSet = CharSet.Auto, SetLastError = true)] private static extern void DnsRecordListFree(IntPtr pRecordList, int FreeType); public List<string> GetMXRecords(string domain) { List<string> records = new List<string>(); IntPtr ptr1 = IntPtr.Zero; IntPtr ptr2 = IntPtr.Zero; MXRecord recMx; try { int result = DnsQuery(ref domain, QueryTypes.DNS_TYPE_MX, QueryOptions.DNS_QUERY_BYPASS_CACHE, 0, ref ptr1, 0); if (result != 0) { if (result == 9003) { //No Record Exists } else { //Some other error } } for (ptr2 = ptr1; !ptr2.Equals(IntPtr.Zero); ptr2 = recMx.pNext) { recMx = (MXRecord)Marshal.PtrToStructure(ptr2, typeof(MXRecord)); if (recMx.wType == 15) { records.Add(Marshal.PtrToStringAuto(recMx.pNameExchange)); } } } finally { DnsRecordListFree(ptr1, 0); } return records; }

    Read the article

  • Initialize Static Array of Structs in C

    - by russell_h
    I implementing a card game in C. There are lots of types of cards and each has a bunch of information, including some actions that will need to be individually scripted associated with it. Given a struct like this (and I'm not certain I have the syntax right for the function pointer) struct CARD { int value; int cost; // This is a pointer to a function that carries out actions unique // to this card int (*do_actions) (struct GAME_STATE *state, int choice1, int choice2); }; I would like to initialize a static array of these, one for each card. I'm guessing this would look something like this int do_card0(struct GAME_STATE *state, int choice1, int choice2) { // Operate on state here } int do_card1(struct GAME_STATE *state, int choice1, int choice2) { // Operate on state here } extern static struct cardDefinitions[] = { {0, 1, do_card0}, {1, 3, do_card1} }; Will this work, and am I going about this the right way at all? I'm trying to avoid huge numbers of switch statements. Do I need to define the 'do_cardN' functions ahead of time, or is there some way to define them inline in the initialization of the struct (something like a lambda function in python)? I'll need read-only access to cardDefinitions from a different file - is 'extern static' correct for that? I know this is a lot of questions rolled into one but I'm really a bit vague about how to go about this. Thanks.

    Read the article

  • Make a form not focusable in C#

    - by Jandex
    Hi! I'm wanting to write a virtual keyboard, like windows onscreen keyboard for touchscreen pcs. But I'm having problem with my virtual keyboard stealing the focus from the application being used. The windows onscreen keyboard mantains the focus on the current application even when the user clicks on it. Is there a way to do the same with windows forms in C#? The only thing I can do for now is to send a keyboard event to an especific application, like notepad in the following code. If I could make the form not focusable, I could get the current focused window with GetForegroundWindow. [DllImport("USER32.DLL", CharSet = CharSet.Unicode)] public static extern IntPtr FindWindow(string lpClassName,string lpWindowName); [DllImport("USER32.DLL")] public static extern bool SetForegroundWindow(IntPtr hWnd); private void button1_Click(object sender, EventArgs e) { IntPtr calculatorHandle = FindWindow("notepad", null); SetForegroundWindow(calculatorHandle); SendKeys.SendWait("111"); } Is there a way this can be done? Any suggestions of a better way to have the form sending keyboard events to the application being used? Thanks!!

    Read the article

  • Calling from C# to C function which accept a struct array allocated by caller

    - by lifey
    I have the following C struct struct XYZ { void *a; char fn[MAX_FN]; unsigned long l; unsigned long o; }; And I want to call the following function from C#: extern "C" int func(int handle, int *numEntries, XYZ *xyzTbl); Where xyzTbl is an array of XYZ of size numEntires which is allocated by the caller I have defined the following C# struct: [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet = System.Runtime.InteropServices.CharSet.Ansi)] public struct XYZ { public System.IntPtr rva; [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 128)] public string fn; public uint l; public uint o; } and a method: [System.Runtime.InteropServices.DllImport(@"xyzdll.dll", CallingConvention = CallingConvention.Cdecl)] public static extern Int32 func(Int32 handle, ref Int32 numntries, [MarshalAs(UnmanagedType.LPArray)] XYZ[] arr); Then I try to call the function : XYZ xyz = new XYZ[numEntries]; for (...) xyz[i] = new XYZ(); func(handle,numEntries,xyz); Of course it does not work. Can someone shed light on what I am doing wrong ?

    Read the article

  • How do C++ compilers actually pass reference parameters?

    - by T.E.D.
    This question came about as a result of some mixed-langauge programming. I had a Fortran routine I wanted to call from C++ code. Fortran passes all its parameters by reference (unless you tell it otherwise). So I thought I'd be clever (bad start right there) in my C++ code and define the Fortran routine something like this: extern "C" void FORTRAN_ROUTINE (unsigned & flag); This code worked for a while but (of course right when I needed to leave) suddenly started blowing up on a return call. Clear indication of a munged call stack. Another engineer came behind me and fixed the problem, declaring that the routine had to be deinfed in C++ as extern "C" void FORTRAN_ROUTINE (unsigned * flag); I'd accept that except for two things. One is that it seems rather counter-intuitive for the compiler to not pass reference parameters by reference, and I can find no documentation anywhere that says that. The other is that he changed a whole raft of other code in there at the same time, so it theoretically could have been another change that fixed whatever the issue was. So the question is, how does C++ actually pass reference parameters? Is it perhaps free to do copy-in, copy-out for small values or something? In other words, are reference parameters utterly useless in mixed-language programming? I'd like to know so I don't make this same code-killing mistake ever again.

    Read the article

  • Send Click Message to another application process

    - by Nazar Hussain
    I have a scenario, i need to send click events to an independent application. I started that application with the following code. private Process app; app = new Process(); app.StartInfo.FileName = app_path; app.StartInfo.WorkingDirectory = dir_path; app.Start(); Now i want to send Mouse click message to that applicaiton, I have specific coordinates in relative to application window. How can i do it using Windows Messaging or any other technique. I used [DllImport("user32.dll")] private static extern void mouse_event(UInt32 dwFlags, UInt32 dx, UInt32 dy, UInt32 dwData, IntPtr dwExtraInfo); It works well but cause the pointer to move as well. So not fit for my need. Then i use. [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)] static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); It works well for minimize maximize, but do not work for mouse events. The codes for mousevents i am using are, WM_LBUTTONDOWN = 0x201, //Left mousebutton down WM_LBUTTONUP = 0x202, //Left mousebutton up WM_LBUTTONDBLCLK = 0x203, //Left mousebutton doubleclick WM_RBUTTONDOWN = 0x204, //Right mousebutton down WM_RBUTTONUP = 0x205, //Right mousebutton up WM_RBUTTONDBLCLK = 0x206, //Right mousebutton do Thanks for the help in advance, and waiting for feedback.

    Read the article

  • C# call a C++ dll get EntryPointNotFoundException

    - by 5YrsLaterDBA
    I was gaven a C++ dll file, a lib file and a header file. I need to call them from my C# application. header file looks like this: class Clog ; class EXPORT_MACRO NB_DPSM { private: string sFileNameToAnalyze ; Clog *pLog ; void write2log(string text) ; public: NB_DPSM(void); ~NB_DPSM(void); void setFileNameToAnalyze(string FileNameToAnalyze) ; int WriteGenbenchData(string& message) ; }; In my C# code, I have those code: internal ReturnStatus correctDataDLL(string rawDataFileName) { if (rawDataFileName == null || rawDataFileName.Length <= 0) { return ReturnStatus.Return_CannotFindFile; } else { setFileNameToAnalyze(rawDataFileName); } string msg = ""; int returnVal = WriteGenbenchData(ref msg); return ReturnStatus.Return_Success; } [DllImport("..\\..\\thirdParty\\cogs\\NB_DPSM.dll")] public static extern void setFileNameToAnalyze(string fileName); [DllImport("..\\..\\thirdParty\\cogs\\NB_DPSM.dll")] public static extern int WriteGenbenchData(ref string message); I got EntryPointNotFoundException at the setFileNameToAnalyze(rawDataFileName); statement. Few questions: do I need to add that lib file into somewhere of my C# project? how? do I need to add the header file into my C# project? how? (no compile error for now) I would like to remove those "..\\..\\thirdParty\\cogs\\" hardcode path. how to this? how to get ride of that EntryPointNotFoundException? thanks,

    Read the article

  • Why does DeviceIoControl throw error 21 (Device Not Ready) from C# when the equivalent in C works fine?

    - by Ragesh
    I'm trying to send an IOCTL_SERVICE_REFRESH command to the GPS Intermediate Driver service using C# like this: handle = CreateFile("GPD0:", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero); if (handle.ToInt32() == INVALID_HANDLE_VALUE) { rc = Marshal.GetLastWin32Error(); return rc; } int numBytesReturned = 0; rc = DeviceIoControl( handle, IOCTL_SERVICE_REFRESH, null, 0, null, 0, ref numBytesReturned, IntPtr.Zero); int error = Marshal.GetLastWin32Error(); GetLastWin32Error always gives me error 21 (device not ready). However, the equivalent call when made from C++ works fine: HANDLE hGPS = CreateFile(L"GPD0:", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (hGPS != INVALID_HANDLE_VALUE) { BOOL ret = DeviceIoControl(hGPS,IOCTL_SERVICE_REFRESH,0,0,0,0,0,0); DWORD err = GetLastError(); } I suspected a problem with the PInvoke signatures, but I can't seem to find anything wrong here: [DllImport("coredll.dll", EntryPoint = "DeviceIoControl", SetLastError = true)] public static extern int DeviceIoControl( IntPtr hDevice, uint dwIoControlCode, byte[] lpInBuffer, int nInBufferSize, byte[] lpOutBuffer, int nOutBufferSize, ref int lpBytesReturned, IntPtr lpOverlapped); [DllImport("coredll.dll", SetLastError = true)] public static extern IntPtr CreateFile( String lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr attr, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile); What am I missing here?

    Read the article

  • Checking if a function has C-linkage at compile-time

    - by scjohnno
    Is there any way to check if a given function is declared with C-linkage (that is, with extern "C") at compile-time? I am developing a plugin system. Each plugin can supply factory functions to the plugin-loading code. However, this has to be done via name (and subsequent use of GetProcAddress or dlsym). This requires that the functions be declared with C-linkage so as to prevent name-mangling. It would be nice to be able to throw a compiler error if the referred-to function is declared with C++-linkage (as opposed to finding out at runtime when a function with that name does not exist). Here's a simplified example of what I mean: extern "C" void my_func() { } void my_other_func() { } // Replace this struct with one that actually works template<typename T> struct is_c_linkage { static const bool value = true; }; template<typename T> void assertCLinkage(T *func) { static_assert(is_c_linkage<T>::value, "Supplied function does not have C-linkage"); } int main() { assertCLinkage(my_func); // Should compile assertCLinkage(my_other_func); // Should NOT compile } Thanks.

    Read the article

  • c# Wrapper to native c++ code, wrapping a parameter which is a pointer to an array

    - by mb300dturbo
    Hi, I have the following simple DLL in c++ un-managed code; extern "C" __declspec(dllexport) void ArrayMultiplier(float (*pointerArray)[3], int scalar, int length); void ArrayMultiplier(float (*pointerArray)[3], int scalar, int length) { for (int i = 0 ; i < length ; length++) { for (int j = 0; j < 3; j++) { pointerArray[i][j] = pointerArray[i][j] * scalar; } } } I have tried writing the following wrapper function for the above in c#: [DllImport("sample.dll")] public static extern void ArrayMultiplier(ref float elements, int scalar, int length); where elements is a 2 dimentional 3x3 array: public float[][] elements = { new float[] {2,5,3}, new float [] {4,8,6}, new float [] {5,28,3} }; The code given above compiles, but the program crashes when the wrapper function is called: Wrapper.ArrayMultiplier(ref elements, scalar, length); Please help me here, and tell me whats wrong with the code above, or how a wrapper can be written for a simple c++ function: void SimpleFunction(float (*pointerToArray)[3]); Thank you all in advance

    Read the article

  • g++ fails mysteriously only if a .h is in a certain directory

    - by ggambett
    I'm experiencing an extremely weird problem in a fresh OSX 10.4.11 + Xcode 2.5 installation. I've reduced it to a minimal test case. Here's test.cpp: #include "macros.h" int main (void) { return 1; } And here's macros.h: #ifndef __JUST_TESTING__ #define __JUST_TESTING__ template<typename T> void swap (T& pT1, T& pT2) { T pTmp = pT1; pT1 = pT2; pT2 = pTmp; } #endif //__JUST_TESTING__ This compiles and works just fine if both files are in the same directory. HOWEVER, if I put macros.h in /usr/include/gfc2 (it's part of a custom library I use) and change the #include in test.cpp, compilation fails with this error : /usr/include/gfc2/macros.h:4: error: template with C linkage I researched that error and most of the comments point to a "dangling extern C", which doesn't seem to be the case at all. I'm at a complete loss here. Is g++ for some reason assuming everything in /usr/include/gfc2 is C even though it's included from a .cpp file that doesn't say extern "C" anywhere? Any ideas? EDIT : It does compile if I use the full path in the #include, ie #include "/usr/include/gfc2/macros.h" EDIT2 : It's not including the wrong header. I've verified this using cpp, g++ -E, and renaming macros.h to foobarmacros.h

    Read the article

  • lstrcpy not updating passed in string

    - by Rorschach
    I'm trying to use kernel32.dll's lstrcpy to get a string from a pointer in C#, but it isn't working. lstrlenA IS working, it gives me the length of the string, so I'm hitting the kernel32.dll at least. lstrcpy is working in the VB6 app I'm converting, so I know it CAN work, but I don't have a clue why it isn't here. The string s never gets filled with the actual string, it just returns the initial padded string. [DllImport("kernel32.dll", EntryPoint = "lstrlenA", CharSet = CharSet.Ansi)] private static extern int lstrlen( int StringPointer ); [DllImport( "kernel32.dll",EntryPoint = "lstrcpyA", CharSet = CharSet.Ansi )] private static extern int lstrcpy(string lpString1, int StringPointer ); private static string StringFromPointer(int pointer) { //.....Get the length of the LPSTR int strLen = lstrlen(pointer); //.....Allocate the NewString to the right size string s = ""; for (int i = 0; i < strLen; i++) s += " "; //.....Copy the LPSTR to the VB string lstrcpy(s, pointer); return s; }

    Read the article

  • How to prevent VC++ 9 linker from linking unnecessary global variables?

    - by sharptooth
    I'm playing with function-level linking in VC++. I've enabled /OPT:REF and /OPT:ICF and the linker is happy to eliminate all unused functions. Not so with variables. The following code is to demonstrate the problem only, I fully understand that actually having code structured that way is suboptimal. //A.cpp SomeType variable1; //B.cpp extern SomeType variable1; SomeType variable2; class ClassInB { //actually uses variable1 }; //C.cpp extern SomeType variable2; class ClassInC { //actually uses variable2; }; All those files are compiled into a static lib. The consumer project only uses ClassInC and links to the static library. Now comes the VC++ 9 linker. First the linker sees that C.obj references variable2 and includes B.obj. B.obj references variable1, so it includes A.obj. Then the unreferenced stuff elimination phase starts. It removes all functions in A.obj and B.obj, but not the variables. Both variable and variable2 are preserved together with their static initializers and deinitializers. That inflates the image size and introduces a delay for running the initializers and deinitializes. The code above is oversimplified, in actual code I really can't move variable2 into C.cpp easily. I could put it into a separate .cpp file, but that looks really dumb. Is there any better option to resolve the problem with Visual C++ 9?

    Read the article

  • Maximize/Minimize is causing Close Button to be re-enabled after disabling it -- Why?

    - by Brainsick
    I have used P/Invoke to call GetSystemMenu and EnableMenuItem (win32api) to disable the close functionality. However, after minimizing or maximizing my Windows Forms application the button is re-enabled. Obviously minimizing or maximizing is causing the behavior, but how? I'm not sure where to look to prevent this behavior. Should I be preventing the maximize and minimize behavior or is there something particularly wrong with the way in which I P/Invoked the calls? Once the application (main form) has loaded, I call the static method from a button click. class PInvoke { // P/Invoke signatures [DllImport("user32.dll")] static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert); [DllImport("user32.dll")] static extern bool EnableMenuItem(IntPtr hMenu, uint uIDEnableItem, uint uEnable); // SysCommand (WM_SYSCOMMAND) constant internal const UInt32 SC_CLOSE = 0xF060; // Constants used with Add/Check/EnableMenuItem internal const UInt32 MF_BYCOMMAND = 0x00000000; internal const UInt32 MF_ENABLED = 0x00000000; internal const UInt32 MF_GRAYED = 0x00000001; internal const UInt32 MF_DISABLED = 0x00000002; /// <summary> /// Sets the state of the Close (X) button and the System Menu close functionality. /// </summary> /// <param name="window">Window or Form</param> /// <param name="bEnabled">Enabled state</param> public static void EnableCloseButton(IWin32Window window, bool bEnabled) { IntPtr hSystemMenu = GetSystemMenu(window.Handle, false); EnableMenuItem(hSystemMenu, SC_CLOSE, MF_BYCOMMAND | (bEnabled ? MF_ENABLED : MF_GRAYED)); } }

    Read the article

  • Some questions about focus on WPF

    - by ThitoO
    Hello, I've a little problem about focus on WPF. I whant to create a window, always on top, and that never get the focus (even if we click on it). Here's my solution : public partial class SkinWindow : Window { public SkinWindow() { InitializeComponent(); Loaded += ( object sender, RoutedEventArgs e ) => SetNoActiveWindow(); } private void SetNoActiveWindow() { WindowInteropHelper helper = new WindowInteropHelper( this ); SetWindowLong( helper.Handle, GWL_EXSTYLE, WS_EX_NOACTIVATE ); LockSetForegroundWindow( LSFW_LOCK ); } const int GWL_EXSTYLE = -20; const int WS_EX_NOACTIVATE = 134217728; const int LSFW_LOCK = 1; [DllImport( "user32" )] public static extern bool LockSetForegroundWindow( uint UINT ); [DllImport( "user32" )] public static extern IntPtr SetWindowLong( IntPtr hWnd, int nIndex, int dwNewLong ); } First problem : It's works, but I've to select an other window to "remove" the focus of my application (after the focus is not gave again, even if I click on my window). Second problem : When I move or resize the window, the modifications happens when I drop the window. Do you have any ideas / links / docs ? Thank you :)

    Read the article

  • Checking if a function has C-linkage at compile-time [unsolvable]

    - by scjohnno
    Is there any way to check if a given function is declared with C-linkage (that is, with extern "C") at compile-time? I am developing a plugin system. Each plugin can supply factory functions to the plugin-loading code. However, this has to be done via name (and subsequent use of GetProcAddress or dlsym). This requires that the functions be declared with C-linkage so as to prevent name-mangling. It would be nice to be able to throw a compiler error if the referred-to function is declared with C++-linkage (as opposed to finding out at runtime when a function with that name does not exist). Here's a simplified example of what I mean: extern "C" void my_func() { } void my_other_func() { } // Replace this struct with one that actually works template<typename T> struct is_c_linkage { static const bool value = true; }; template<typename T> void assertCLinkage(T *func) { static_assert(is_c_linkage<T>::value, "Supplied function does not have C-linkage"); } int main() { assertCLinkage(my_func); // Should compile assertCLinkage(my_other_func); // Should NOT compile } Is there a possible implementation of is_c_linkage that would throw a compiler error for the second function, but not the first? I'm not sure that it's possible (though it may exist as a compiler extension, which I'd still like to know of). Thanks.

    Read the article

  • IIS reverse proxy to windows authenticated internal site

    - by keithwarren7
    I have an internal windows authenticated website that I need to expose anonymously to external users. extern: http://foo.com/ (public) intern: http://privatefoo/ (requires windows auth) I want people hitting foo.com to see no security prompt, just get access to privatefoo - I know this is possible in a simple reverse proxy setup but does anyone know how to make the proxy provide windows credentials?

    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

  • C++ SDL State Machine Segfault

    - by user1602079
    The code compiles and builds fine, but it immediately segfaults. I've looked at this for a while and have no idea why. Any help is appreciated. Thank you! Here's the code: main.cpp #include "SDL/SDL.h" #include "Globals.h" #include "Core.h" #include "GameStates.h" #include "Introduction.h" int main(int argc, char** args) { if(core.Initilize() == false) { SDL_Quit(); } while(core.desiredstate != core.Quit) { currentstate->EventHandling(); currentstate->Logic(); core.ChangeState(); currentstate->Render(); currentstate->Update(); } SDL_Quit(); } Core.h #ifndef CORE_H #define CORE_H #include "SDL/SDL.h" #include <string> class Core { public: SDL_Surface* Load(std::string filename); void ApplySurface(int X, int Y, SDL_Surface* source, SDL_Surface* destination); void SetState(int newstate); void ChangeState(); enum state { Intro, STATES_NULL, Quit }; int desiredstate, stateID; bool Initilize(); }; #endif Core.cpp #include "Core.h" #include "SDL/SDL.h" #include "Globals.h" #include "Introduction.h" #include <string> /* Initilizes SDL subsystems */ bool Core::Initilize() { //Inits subsystems, reutrns false upon error if(SDL_Init(SDL_INIT_EVERYTHING) == -1) { return false; } SDL_WM_SetCaption("Game", NULL); return true; } /* Loads surfaces and optimizes them */ SDL_Surface* Core::Load(std::string filename) { //The surface to be optimized SDL_Surface* original = SDL_LoadBMP(filename.c_str()); //The optimized surface SDL_Surface* optimized = NULL; //Optimizes the image if it loaded properly if(original != NULL) { optimized = SDL_DisplayFormat(original); SDL_FreeSurface(original); } else { //returns NULL upon error return NULL; } return optimized; } /* Blits surfaces */ void Core::ApplySurface(int X, int Y, SDL_Surface* source, SDL_Surface* destination) { //Stores the coordinates of the surface SDL_Rect offsets; offsets.x = X; offsets.y = Y; //Bits the surface if both surfaces are present if(source != NULL && destination != NULL) { SDL_BlitSurface(source, NULL, destination, &offsets); } } /* Sets desiredstate to newstate */ void Core::SetState(int newstate) { if(desiredstate != Quit) { desiredstate = newstate; } } /* Changes the game state */ void Core::ChangeState() { if(desiredstate != STATES_NULL && desiredstate != Quit) { delete currentstate; switch(desiredstate) { case Intro: currentstate = new Introduction(); break; } stateID = desiredstate; desiredstate = core.STATES_NULL; } } Globals.h #ifndef GLOBALS_H #define GLOBALS_H #include "SDL/SDL.h" #include "Core.h" #include "GameStates.h" extern SDL_Surface* screen; extern Core core; extern GameStates* currentstate; #endif Globals.cpp #include "Globals.h" #include "SDL/SDL.h" #include "GameStates.h" SDL_Surface* screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE); Core core; GameStates* currentstate = NULL; GameStates.h #ifndef GAMESTATES_H #define GAMESTATES_H class GameStates { public: virtual void EventHandling() = 0; virtual void Logic() = 0; virtual void Render() = 0; virtual void Update() = 0; }; #endif Introduction.h #ifndef INTRODUCTION_H #define INTRODUCTION_H #include "GameStates.h" #include "Globals.h" class Introduction : public GameStates { public: Introduction(); private: void EventHandling(); void Logic(); void Render(); void Update(); ~Introduction(); SDL_Surface* test; }; #endif Introduction.cpp #include "SDL/SDL.h" #include "Core.h" #include "Globals.h" #include "Introduction.h" /* Loads all the assets */ Introduction::Introduction() { test = core.Load("test.bmp"); } void Introduction::EventHandling() { SDL_Event event; while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: core.SetState(core.Quit); break; } } } void Introduction::Logic() { //to be coded } void Introduction::Render() { core.ApplySurface(30, 30, test, screen); } void Introduction::Update() { SDL_Flip(screen); } Introduction::~Introduction() { SDL_FreeSurface(test); } Sorry if the formatting is a bit off... Having to put four spaces for it to be put into a code block offset it a bit. I ran it through gdb and this is what I got: Program received signal SIGSEGV, Segmentation fault. 0x0000000000400e46 in main () Which isn't incredibly useful... Any help is appreciated. Thank you!

    Read the article

  • Getting Current Native Thread

    - by Ricardo Peres
    The native OS threads running in the current process are exposed through the Threads property of the Process class. Please note that this is not the same as a managed thread, these are the actual native threads running on the operating system. In order to get a pointer to the current executing thread, we must use P/Invoke. Here's how we do it: [DllImport("kernel32.dll")] public static extern UInt32 GetCurrentThreadId(); UInt32 id = GetCurrentThreadId(); ProcessThread thread = Process.GetCurrentProcess().Threads.Cast().Where(t = t.Id == id).Single(); SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/2.0.320/scripts/clipboard.swf'; SyntaxHighlighter.brushes.CSharp.aliases = ['c#', 'c-sharp', 'csharp']; SyntaxHighlighter.all();

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >