vendredi 26 juin 2015

How to Declare a Delegate at runtime and call it method ar runtime in C#?

Consider the below C # code:

public partial class Form1 : Form {

    [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);


    delegate int MyFunc(IntPtr a);




   // private static extern IntPtr GetForegroundWindow();



    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

    String strDLL = "user32.dll";
    // Load the DLL library.
    IntPtr iModule = LoadLibrary(strDLL);

    // Retrieve the function pointer.
    IntPtr pProc = GetProcAddress(iModule, "SetForegroundWindow");

      // Delegate method.

        // Convert the function pointer to delegate method.
        MyFunc pFunc = (MyFunc)Marshal.GetDelegateForFunctionPointer(pProc, typeof(MyFunc));

        // Execute the function.
        int iRes = pFunc.Invoke((IntPtr)132462);


    // Unload the DLL library.
    FreeLibrary(iModule);
}







}

}

Here on Button click i want to dynamically declare the delegate and call the method at runtime as per the data from some textbox .

How can i do that





Aucun commentaire:

Enregistrer un commentaire