2012-11-14 84 views
2

我不熟悉構建小示例應用程序的WindowsForms。FindWindow在當前上下文中不存在

我試圖構建一個應用程序,鍵入文本到記事本窗口中,並且當它從dll導入時出現錯誤FindWindow does not exist in current context

namespace WindowsFormsApplication1 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void MenuAbout_Click(object sender, System.EventArgs e) 
     { 
      Form1 frm = new Form1(); 
      frm.ShowDialog(); 
     } 

     private void Launch_Click(object sender, System.EventArgs e) 
     { 

      // find window handle of Notepad 
      IntPtr handle = FindWindow("Notepad", "Untitled - Notepad"); 
      if (!handle.Equals(IntPtr.Zero)) 
      { 
       // activate Notepad window 
       if (SetForegroundWindow(handle)) 
       { 
        // send "Hello World!" 
        SendKeys.Send("Hello World!"); 
        // send key "Tab" 
        SendKeys.Send("{TAB}"); 
        // send key "Enter" 
        SendKeys.Send("{ENTER}"); 
       } 
      } 
      //Process.Start(@"D:\\32-Bit Programs\\StarCraft II\\Support\\SC2Switcher.exe"); 
     } 


     [DllImport("user32.dll", EntryPoint = "FindWindow")] 
     private extern IntPtr FindWindow(string lp1, string lp2); 

     [DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)] 
     [return: MarshalAs(UnmanagedType.Bool)] 
     private extern bool SetForegroundWindow(IntPtr hWnd); 
    } 
} 

回答

11

您導入的方法must also be static

[DllImport("user32.dll", EntryPoint = "FindWindow")] 
    private static extern IntPtr FindWindow(string lp1, string lp2); 

    [DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)] 
    [return: MarshalAs(UnmanagedType.Bool)] 
    private static extern bool SetForegroundWindow(IntPtr hWnd); 
相關問題