开发者

is there a way to switch from one app to another in C#?

开发者 https://www.devze.com 2023-03-26 02:42 出处:网络
Hi I have a new question for all fellow programmers to solve. Is there a way that I can press a button or have a timer on that will fire an event that will make my app switch from one app to another?f

Hi I have a new question for all fellow programmers to solve. Is there a way that I can press a button or have a timer on that will fire an event that will make my app switch from one app to another? for example lets say I want to make a app that when i press a button it will switch from the current app to anot开发者_JS百科her app that is running like notepad or a game or something.

If there is a way to open a specific app by its name that would be great to, thanks.

PS: I already know how to code a timer so you don't have to post one if you don't want to.


Using the two WinAPI functions FindWindow and SetFocus, you can achieve your desired goal:

[DllImport("user32.dll")]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

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

For example, to set a notepad window with the title "" to the foreground, you can use the following code:

SetFocus(FindWindow("Notepad", "Untitled - Notepad"));

If you don't know the form's name, then you can enumerate the windows using other WinAPI functions.


Alternatively, you can use the Interaction.AppActivate() method from Microsoft.VisualBasic.dll, found in namespace Microsoft.VisualBasic if you reference it.

Just simple call Interaction.AppActivate("window title") or Interaction.AppActivate(iPID).

The appropriate documentation for this method can be found here.


You can use Pinvoke to call the SetFocus function which takes a WindowHandle and sets the keyboard focus to that screen.

http://msdn.microsoft.com/en-us/library/ms646312(v=vs.85).aspx

http://www.pinvoke.net for more information on how to use Pinvoke.

http://support.microsoft.com/kb/147659 : A good article if you're unsure of what the window title is (if you do then you can just get all the window handles and then use GetWindowName() to get the window name and check if that's the one you want, GetWindowName also takes a window handle)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号