GetModuleHandle(null) equivalent in C#

Currently I'm using DLLImport for the method:

GetModuleHandle(null)

I would prefer moving away from it. Does .NET have an equivalent

There's a method: RuntimeTypeHandle.GetModuleHandle () but that's not it, or is it




Answer this question

GetModuleHandle(null) equivalent in C#

  • EgyBoy

    Just-A-Nerd wrote:
    I like your sarcasm, but it does give me the answer I wanted (as usual I searched for something quite different when I found it) and since others might ask the same question, I post it here - so you don't get too tired answering stupid questions


    Just-A-Nerd! It wasn't sarcastic, there are some user that found an answer for there problem but never post it in the thread and just leave it open.

    So, i just wanne thank you for replying the correct answer!


  • angsram

    As far as i know there is no managed class available. Just use the p/invoke to accomplashe your goal.


    [DllImport("kernel32.dll")]
    public static extern IntPtr GetModuleHandle(string lpModuleName);



  • GeoffNin

    First, the universal syntax of my method:

    Marshal.GetHINSTANCE(this.GetType().Module)

    should get a modulehandle to the current module.

    About GetModuleHandle(null): I actually think it gives a modulehandle for the .NET Runtime module, which is normally not what we want.



  • Tom2005

    What do you then do with the handle you obtain .NET doesn't have a direct equivalent but there may be other ways to accomplish the end result.



  • Claudeb1965

    I didn't see PJ's reply as sarcastic.

    It's worth pointing out that your solution doesn't do exactly the same thing as the original code. GetModuleHandle(NULL) returns the base address of the startup executable. Marshal.GetHINSTANCE(typeof(MyClass).Module) returns the base address of the executable containing MyClass. They are only the same if in fact MyClass is in the startup EXE assembly.



  • John Schmiederer

    Thank you very much for the reply with the correct answer!


  • Staf-fan

    Sorry for misunderstanding, PJ - and you're welcome :-)

    And thanks Mattias Sjogren, for pointing out the difference. However, my code is working both inside and outside the Ide - which it also did with GetModuleHandle(null) - so I'll stick with it.



  • ngo the an

    I like your sarcasm, but it does give me the answer I wanted (as usual I searched for something quite different when I found it) and since others might ask the same question, I post it here - so you don't get too tired answering stupid questions



  • Tejal

    Actually I found a solution:

    Marshal.GetHINSTANCE(typeof(MyClass).Module)



  • GetModuleHandle(null) equivalent in C#