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

标签 c# .net focus exe launch

我一直在尝试使用互斥体的代码,但我无法在单击按钮后打开我的 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/

相关文章:

c# - 尝试从C#中的参数读取路径时感到沮丧

C# 内存地址扩展与代码

java - 疯狂的想法 : Connect . NET 和 SAP with SAP JCo 使用 IKVM.NET

c# - Silverlight 和异步调用的问题

javascript - 悬停、焦点操作时的 JavaScript

c++ - 如何返回当前具有焦点的QWidget

c# - 另一个“为此有设计模式吗?”

c# - 将 arraylist 添加到另一个具有不同值的 arraylist

.net - 与Episerver进行TDD

javascript - 如果 javascript 验证失败,则聚焦文本字段