Posts Tagged ‘C#/.NET’

C#单实例运行实现

星期一, 2月 26th, 2007

在某些情况我们要求应用程序只能运行一次,后运行的实例要把之前运行的程序激活并自己退出。
在网上搜索了一些实现并根据自己的理解重新整理得出下面的实现代码:

1. API函数的声明
// Uses to active the exist window
[DllImport("User32.dll")]
public static extern void SetForegroundWindow(IntPtr hwnd);

[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);

// 0-Hidden, 1-Centered, 2-Minimized, 3-Maximized
private const int WS_SHOWNORMAL = 3;

2. 查找并激活已经存在的程序(仅应用于进程名相同的程序)
///

/// Finds the running instance.
///

/// true if exist a running instace, otherwise false
private static bool ExistRunningInstance()
{
Process currentProcess = Process.GetCurrentProcess();
Process[] procList = Process.GetProcessesByName(currentProcess.ProcessName);

foreach (Process proc in procList)
{
// Found a running instance
if (proc.Id != currentProcess.Id)
{
// Active the running instance
ShowWindowAsync(proc.MainWindowHandle, WS_SHOWNORMAL);
SetForegroundWindow(proc.MainWindowHandle);

return true;
}
}

return false;
}

3. 在Main函数入口判断
[STAThread]
static void Main()
{
// Control only one instance with the same process name can run
if (ExistRunningInstance())
{
Environment.Exit(1); // App is running, exit
}

// 程序真正运行的代码
}

C#多线程操作界面控件的解决方案

星期一, 2月 26th, 2007

C#2005后不再支持多线程直接访问界面的控件(界面创建线程与访问线程不是同一个线程),不过可以使用delegate来解决:

1. 声明一个delegate和定义一个delegate的实现函数
delegate void ShowProgressDelegate(int newPos);
private void ShowProgress(int newPos)
{
// 判断是否在线程中访问
if (!_progressBar.InvokeRequired)
{
// 不是的话直接操作控件
_progressBar.Value = newPos;
}
else
{
// 是的话启用delegate访问
ShowProgressDelegate showProgress = new ShowProgressDelegate(ShowProgress);
// 如使用Invoke会等到函数调用结束,而BeginInvoke不会等待直接往后走
this.BeginInvoke(showProgress, new object[] { newPos });
}
}

2. 定义线程函数(在另一个线程中可以对界面控件进读操作)
private void ProgressStart()
{
while (true)
{
int newPos = _progressBar.Value + 10;

if (newPos > _progressBar.Maximum)
{
newPos = _progressBar.Minimum;
}
Trace.WriteLine(string.Format("Pos: {0}", newPos));

// 这里直接调用方法,由其内部自动判断是否启用delegate
ShowProgress(newPos);
Thread.Sleep(100);
}
}

3. 线程的启动和终止
private Thread _progressThread;
_progressThread = new Thread(new ThreadStart(ProgressStart));
// 可选,功用:即使该线程不结束,进程也可以结束
_progressThread.IsBackground = true;
_progressThread.Start();

_progressThread.Abort();
// 可选,功用:等到线程结束才继续
_progressThread.Join();
_progressThread = null;