Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FindWindow does not exist in current context

Tags:

c#

I'm new to WindowsForms building a small sample application.

I'm trying to build an application that types text into a Notepad window and I'm getting the error FindWindow does not exist in current context when it's being imported from the 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);
    }
}
like image 207
Ben Avatar asked Dec 10 '25 13:12

Ben


1 Answers

Your imported methods 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);
like image 84
Blorgbeard Avatar answered Dec 12 '25 01:12

Blorgbeard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!