2

我是构建小型示例应用程序的 WindowsForms 新手。

我正在尝试构建一个在记事本窗口中键入文本的应用程序,并且在FindWindow does not exist in current context从 dll 导入它时出现错误。

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);
    }
}
4

1 回答 1

11

您导入的方法也必须是静态的:

    [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);
于 2012-11-14T01:47:08.917 回答