Csharp/CSharp Tutorial/Windows/DLL

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Call DLL API to move file

<source lang="csharp">using System; using System.IO; using System.Runtime.InteropServices;

   class Tester
   {
       [DllImport("kernel32.dll", EntryPoint = "MoveFile",ExactSpelling = false, CharSet = CharSet.Unicode,SetLastError = true)]
       static extern bool MoveFile(string sourceFile, string destinationFile);
       public static void Main()
       {
           ExploreDirectory(new DirectoryInfo("c:\\"));
       }
       private static void ExploreDirectory(DirectoryInfo dir)
       {
           string newDirectory = "newTest";
           DirectoryInfo newSubDir =dir.CreateSubdirectory(newDirectory);
           FileInfo[] filesInDir = dir.GetFiles();
           foreach (FileInfo file in filesInDir)
           {
               string fullName = newSubDir.FullName + "\\" + file.Name;
               file.CopyTo(fullName);
               Console.WriteLine(file.FullName);
           }
           filesInDir = newSubDir.GetFiles();
           int counter = 0;
           foreach (FileInfo file in filesInDir)
           {
               string fullName = file.FullName;
               if (counter++ % 2 == 0)
               {
                   Tester.MoveFile(fullName, fullName + ".bak");
                   Console.WriteLine("{0} renamed to {1}",fullName, file.FullName);
               }else{
                   file.Delete();
                   Console.WriteLine("{0} deleted.",fullName);
               }
           }
           newSubDir.Delete(true);
       }
   }</source>

Compile to dll

<source lang="csharp">// compile with: csc /r:..\logdriver.dll /target:library logaddintofile.cs using System; using System.Collections; using System.IO; public class LogAddInToFile {

   StreamWriter streamWriter;
   
   public LogAddInToFile()
   {
       streamWriter = File.CreateText(@"logger.log");
       streamWriter.AutoFlush = true;
   }
   
   public void Log(string message)
   {
       streamWriter.WriteLine(message);
   }

}</source>

Fiber

<source lang="csharp">using System; using System.Drawing; using System.Collections; using System.ruponentModel; using System.Windows.Forms; using System.Data; using System.Runtime.InteropServices; using System.Threading; using System.Diagnostics; public class fmrFibers : System.Windows.Forms.Form {

   private System.Windows.Forms.ListBox lstFibers;
   [DllImport("kernel32.dll")]
   extern static IntPtr ConvertThreadToFiber(int fiberData);
   [DllImport("kernel32.dll")]
   extern static IntPtr CreateFiber(int size, System.Delegate function, int handle);
   [DllImport("kernel32.dll")]
   extern static IntPtr SwitchToFiber(IntPtr fiberAddress);
   [DllImport("kernel32.dll")]
   extern static void DeleteFiber(IntPtr fiberAddress);
   [DllImport("kernel32.dll")]
   extern static int GetLastError();
   delegate void SetTextOutputToEventLog(int number);
   public fmrFibers() {
       this.lstFibers = new System.Windows.Forms.ListBox();
       this.SuspendLayout();
       this.lstFibers.Size = new System.Drawing.Size(320, 212);
       this.ResumeLayout(false);
       Thread t1 = new Thread(new ThreadStart(NewThreadToFiberExecution));
       t1.Start();
   }
   void OutputLog(int fiberNumber) {
       this.Invoke(new AddToListBox(SetText), new object[] { fiberNumber });
       SwitchToFiber(obj);
   }
   void SetText(int message) {
       lstFibers.Items.Add("Fiber " + message.ToString() + " added this");
   }
   delegate void AddToListBox(int message);
   System.IntPtr obj;
   void NewThreadToFiberExecution() {
       try {
           SetTextOutputToEventLog stof = new SetTextOutputToEventLog(OutputLog);
           obj = ConvertThreadToFiber(0);
           long l1 = GetLastError();
           System.IntPtr retVal1 = CreateFiber(500, stof, 1);
           if (GetLastError() != 0) throw new Exception("Create Fiber failed!!");
           IntPtr fiber1return = SwitchToFiber(retVal1);
           if (GetLastError() != 0) throw new Exception("Create Fiber failed!!");
           DeleteFiber(retVal1);
       } catch (Exception e) {
           throw e;
       }
   }
   [STAThread]
   static void Main() {
       Application.Run(new fmrFibers());
   }

}</source>

Invoke MessageBox in Dll

<source lang="csharp">using System; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Text;

   class Program
   {
       [DllImport("user32.dll")]
       public static extern int MessageBox(IntPtr hwnd, String text, String caption, uint type);
       static void Main(string[] args)
       {
           MessageBox(new IntPtr(0), "Greetings from Platform Invoke", "Platform Invoke", 0);
       }
   }</source>

Marshal a function from Dll to a delegate

<source lang="csharp">using System; using System.Threading; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Text;

   class Program
   {
       [DllImport("kernel32.dll")]
       static extern IntPtr LoadLibrary(string dllName);
       [DllImport("kernel32.dll")]
       static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
       delegate int MessageBoxDelegate(IntPtr hwnd,
           [MarshalAs(UnmanagedType.LPWStr)]string text,
           [MarshalAs(UnmanagedType.LPWStr)]string caption,
           int type);
       static void Main(string[] args)
       {
           IntPtr userApi = LoadLibrary("user32.dll");
           IntPtr msgBoxAddress = GetProcAddress(userApi, "MessageBoxW"); // unicode (wide) message box
           MessageBoxDelegate mbd = (MessageBoxDelegate)Marshal.GetDelegateForFunctionPointer(msgBoxAddress,typeof(MessageBoxDelegate));
           mbd(IntPtr.Zero, "A", "B", 0);
           DoSomething(mbd);
       }
       static void DoSomething(MessageBoxDelegate mbd)
       {
           mbd(IntPtr.Zero, "Work completed.", "Work Progress", 0);
       }
   }</source>

Using load library from Dll

<source lang="csharp">using System; using System.Threading; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Text;

   class Program
   {
       [DllImport("kernel32.dll")]
       static extern IntPtr LoadLibrary(string dllName);
       [DllImport("kernel32.dll")]
       static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
       delegate int MessageBoxDelegate(IntPtr hwnd,
           [MarshalAs(UnmanagedType.LPWStr)]string text,
           [MarshalAs(UnmanagedType.LPWStr)]string caption,
           int type);
       static void Main(string[] args)
       {
           IntPtr userApi = LoadLibrary("user32.dll");
           IntPtr msgBoxAddress = GetProcAddress(userApi, "MessageBoxW"); // unicode (wide) message box
           MessageBoxDelegate mbd = (MessageBoxDelegate)Marshal.GetDelegateForFunctionPointer(msgBoxAddress,typeof(MessageBoxDelegate));
           mbd(IntPtr.Zero, "A", "B", 0);
           DoSomething(mbd);
       }
       static void DoSomething(MessageBoxDelegate mbd)
       {
           mbd(IntPtr.Zero, "Work completed.", "Work Progress", 0);
       }
   }</source>