读书人

让一个窗体只显示一个,该怎么解决

发布时间: 2013-07-11 15:38:46 作者: rapoo

让一个窗体只显示一个
我写了一个窗体单例模式但是解决不了,我要的是一个窗体只能显示一个,当关闭时下次还可以打开,不是限制只能打开一次,可以打开多次但是每次只能显示一个,有明白的没,说说怎么解决吧
[解决办法]
弄个状态不行吗
[解决办法]

引用:
弄个状态不行吗

+1
[解决办法]

[STAThread]
bool isRuned ;
try
{
System.Threading.Mutex mutex = new System.Threading.Mutex(true,"OnlyRunOneInstance", out isRuned);
if (isRuned)
{
Form frm = new Form();
if (frm.IsDisposed == false)
Application.Run(frm);
mutex.ReleaseMutex();
Application.Exit();
}
else
{
MessageBox.Show("已启动!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception e)
{
}

试试这个
[解决办法]
在打开之前,判断已经打开的窗口类型是否为需要打开的窗口类型即可。
如果是WinForm(也可能是WPF,你未说明),那么可以这么写:
bool isfind = false;
foreach (Form f in Application.OpenForms)
{
if(f.GetType() == typeof(MyForm))
{
isfind = true;
//说明找到了,做对应的处理,然后跳出循环

break;
}
}

[解决办法]
.lz的描述 不就是单例模式 可以解决么?

但是,再看了 1楼的代码, 我完全就不知道lz说的是啥了。。。。

当 if (showCount>=1) 的时候 this.Close();



然后在窗体关闭事件中 showCount = 0; 非常的不解。


请问一下lz你是怎么调用这个窗体的?
[解决办法]



using System;
using System.Collections.Generic;
using System.Windows.Forms;

using System.Runtime.InteropServices;
using System.Diagnostics;

namespace frmMain
{
static class Program
{
private const int WS_SHOWNORMAL = 1;
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{

Process instance = GetRunningInstance();
if (instance == null)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmMain());

}

else
{
HandleRunningInstance(instance);
}
}

/// <summary>
/// 获取当前是否具有相同进程。
/// </summary>


/// <returns></returns>
public static Process GetRunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(current.ProcessName);
//遍历正在有相同名字运行的例程
foreach (Process process in processes)
{
//忽略现有的例程
if (process.Id != current.Id)
//确保例程从EXE文件运行
if (System.Reflection.Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
return process;
}
return null;
}
/// <summary>
/// 激活原有的进程。
/// </summary>
/// <param name="instance"></param>
public static void HandleRunningInstance(Process instance)
{
ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);
SetForegroundWindow(instance.MainWindowHandle);
}

}
}


[解决办法]
http://bbs.csdn.net/topics/390510753

读书人网 >C#

热点推荐