zoy*_*oya 5 .net c# exe focus launch
我一直在尝试使用互斥体的代码,但在单击按钮后我无法打开我的exe,我成功地没有在单击按钮时在任务栏上创建应用程序的多个条目,但我的应用程序仅在我关闭表单时启动。我想要在单击按钮时启动我的应用程序,如果应用程序已经启动,那么我需要专注于以前正在运行的应用程序..我如何才能解决我启动以及聚焦并再次重新打开该应用程序的需要..我正在向您发送我在按钮单击事件上使用的代码,请修改我的错误...
在program.cs处编码
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
System.Diagnostics.Process.Start("filename.exe");
}
Run Code Online (Sandbox Code Playgroud)
:
在 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());
}
}
Run Code Online (Sandbox Code Playgroud)
这能够找到并切换到与您尝试启动的进程相匹配的已运行进程。
[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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6521 次 |
| 最近记录: |