c# 程序只运行一次的处理方法
方法一:遍历正在有相同名字运行的例程
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace DHPSS.COM
{
/// <summary>
/// c#程序只运行一次,C#例程只运行一次
/// http://blog.csdn.net/nnsword
/// QQ:16349023
/// </summary>
public class CHandleRunningPro
{
/// <summary>
/// const int, ShowWindowAsync 使用时的参数,让窗体正常显示确保没有隐藏和最小化。
/// </summary>
private const int WS_SHOWNORMAL = 1;
/// <summary>
/// 功能:遍历所有运行的例程,判断是否已经有相同名字的例程。
/// 实现:遍历所有运行的例程,如果有与自己名字相同的比较 ID 是否相同。
/// 如果ID不同说明已经有实例在运行,则把该实例返回。
/// 如果没有则返回 null
/// </summary>
/// <returns>有相同名字的例程返回其 process,否则返回null</returns>
private Process GetRunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(current.ProcessName);
//遍历正在有相同名字运行的例程
foreach (Process process in processes)
{
//忽略现有的例程
if (process.Id != current.Id)
{
return process;
}
}
//没有其它的例程,返回Null
return null;
}
//接下来调用两个WinAPI,其功能将在包装方法中描述,
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
//以上的方法声明为私有,对其进一步包装,
相关文档:
//获取包含清单的已加载文件的路径或 UNC 位置。
public static string sApplicationPath = Assembly.GetExecutingAssembly ( ).Location;
//result: X:\xxx\xxx\xxx.dll (.dll文件所在的目录+.dll文件名)
//获取当前进程的完整路径,包含文件名(进程名)。
string str = this.GetType ( ).Assembly.Location;
//result ......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
//sqlserver身份验证
//string sqlconn = "ser ......
关于使用到了两个C#关键字this和base。
1,C# "this " keyword
其作用引用类的当前实例,其实看了下面这个例子就好理解了。
主要三个作用:当前实例、参数传递和索引器
1.1 当前实例
class Team
{
///成员变量
private string name;
///构造函数
......
public string WriteXML(string[] values, int flag)
{
//如果flag==0则为第一次运行需要初始化XML文件
if (flag == 0)
{
//生在随机文件名
string dateName = System.DateTime.Now.ToString("yyyyMMddHHmmss");
......