2013-10-18 36 views
23

我發現了很多關於它的問題,但沒有人解釋我可以如何使用它。如何在C#中使用[DllImport(「」)]?

我有這樣的:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Runtime.InteropServices; 
using System.Windows.Forms; 
using Microsoft.FSharp.Linq.RuntimeHelpers; 
using System.Diagnostics; 
using System.Runtime.InteropServices; 
using System.IO; 

public class WindowHandling 
{ 
    public void ActivateTargetApplication(string processName, List<string> barcodesList) 
     { 
      [DllImport("User32.dll")] 
      public static extern int SetForegroundWindow(IntPtr point); 
      Process p = Process.Start("notepad++.exe"); 
      p.WaitForInputIdle(); 
      IntPtr h = p.MainWindowHandle; 
      SetForegroundWindow(h); 
      SendKeys.SendWait("k"); 
      IntPtr processFoundWindow = p.MainWindowHandle; 
     } 
} 

有人可以幫助我理解爲什麼它給了我一個錯誤的DllImport線和上線public static

有沒有人有想法,我該怎麼辦? 謝謝。

+1

什麼錯誤? –

+0

除了@vcsjones提到的外,還有多個問題。你有使用此的User32.dll。還要檢查你寫過[DllImport]語句的地方,它的地方不對。 –

+2

@PM。 User32.dll是一個非常標準的Win32 DLL,它總是在SysWow64或System32中,因此找到它應該不會有問題。如果在搜索序列中存在另一個具有相同名稱的「更接近」的DLL,它可能會發現*錯誤*,但這會給大多數程序帶來災難。 – vcsjones

回答

48

你不能在一個方法或任何其他具有屬性的方法中聲明一個局部方法extern。將您的DLL導入到類中:

using System.Runtime.InteropServices; 


public class WindowHandling 
{ 
    [DllImport("User32.dll")] 
    public static extern int SetForegroundWindow(IntPtr point); 

    public void ActivateTargetApplication(string processName, List<string> barcodesList) 
    { 
     Process p = Process.Start("notepad++.exe"); 
     p.WaitForInputIdle(); 
     IntPtr h = p.MainWindowHandle; 
     SetForegroundWindow(h); 
     SendKeys.SendWait("k"); 
     IntPtr processFoundWindow = p.MainWindowHandle; 
    } 
} 
+22

您還必須在Microsoft Visual Studio中使用'System.Runtime.InteropServices' – Cullub

+0

您還必須使用'System.Diagnostics'才能使用Process對象 – Wigwam