gpt4 book ai didi

c# - 如何在 c#.net3.5 中设置焦点并在按钮单击事件上启动已经运行的应用程序?

转载 作者:太空狗 更新时间:2023-10-30 01:27:50 26 4
gpt4 key购买 nike

我一直在尝试使用互斥体的代码,但我无法在单击按钮后打开我的 exe我成功地没有在单击按钮时在任务栏上创建应用程序的多个条目,但我的应用程序仅在我关闭表单时启动。我想在单击按钮时启动我的应用程序,如果应用程序已经启动,那么我需要关注之前运行的应用程序。我怎么能解决我的需要启动以及 focusin 并再次重新打开该应用程序..我正在向您发送我在按钮单击事件上使用的代码,请修改我的错误...

在 program.cs 中编码

static void Main()  
{

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);

Application.Run(new Form1());
System.Diagnostics.Process.Start("filename.exe");
}

:

编码在 form1.cs 完成

private void button1_Click(object sender, EventArgs e)
{
try
{
bool createdNew;
Mutex m = new Mutex(true, "e-Recording", out createdNew);
System.Diagnostics.ProcessStartInfo f = new System.Diagnostics.ProcessStartInfo("C:\\windows\\system32\\rundll32.exe", "C:\\windows\\system32\\shimgvw.dll,ImageView_Fullscreen " + "filename.exe".TrimEnd(null));

if (createdNew) Launch();

else
{
MessageBox.Show("e-Recording is already running!", "Multiple Instances");
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}

最佳答案

这能够找到并切换到与您尝试启动的进程相匹配的已经运行的进程。

[DllImport( "user32.dll" )]
public static extern bool ShowWindowAsync( HandleRef hWnd, int nCmdShow );
public const int SW_RESTORE = 9;

public void SwitchToCurrent() {
IntPtr hWnd = IntPtr.Zero;
Process process = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName( process.ProcessName );
foreach ( Process _process in processes ) {
// Get the first instance that is not this instance, has the
// same process name and was started from the same file name
// and location. Also check that the process has a valid
// window handle in this session to filter out other user's
// processes.
if ( _process.Id != process.Id &&
_process.MainModule.FileName == process.MainModule.FileName &&
_process.MainWindowHandle != IntPtr.Zero ) {
hWnd = _process.MainWindowHandle;

ShowWindowAsync( NativeMethods.HRef( hWnd ), SW_RESTORE );
break;
}
}
}

关于c# - 如何在 c#.net3.5 中设置焦点并在按钮单击事件上启动已经运行的应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2197620/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com