Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

c# - FindWindow and SetForegroundWindow alternatives?

I am searching for alternatives to the old User32.dll version of switching to a different application with FindWindow() and SetForegroundWindow().

I did find an alternative to the first with the usage of Process.GetProcessesByName() but I do not see the corresponding method to switch (set active/foreground) to that application.

Is there a way of doing that without using the old way with the User32.dll?

Thank you for your help.

EDIT

I accepted the answer of @Sorceri although it is not the answer I was looking for.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Answer: No.

But, to help the next wonderer looking to find a window and activate it from C# here's what you have to do:

[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);

void ActivateApp(string processName)
{
    Process[] p = Process.GetProcessesByName(processName);

    // Activate the first application we find with this name
    if (p.Count() > 0)
        SetForegroundWindow(p[0].MainWindowHandle);
}

To bring notepad to the front, for example, you would call:

ActivateApp("notepad");

As a side note - for those of you who are trying to bring a window within your application to the foreground just call the Activate() method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...