Domanda

Vorrei sapere come posso controllare un programma in una posizione specifica se è in esecuzione. Per esempio ci sono due posizioni per test.exe in c: \ LOC1 \ test.exe e c: \ LOC2 \ test.exe. Volevo solo sapere se c: \ LOC1 \ test.exe è in esecuzione e non tutte le istanze di test.exe

.
È stato utile?

Soluzione

bool isRunning = Process.GetProcessesByName("test")
                .FirstOrDefault(p => p.MainModule.FileName.StartsWith(@"c:\loc1")) != default(Process);

Altri suggerimenti

Questo è il mio miglioramento della funzione:

private bool ProgramIsRunning(string FullPath)
{
    string FilePath =  Path.GetDirectoryName(FullPath);
    string FileName = Path.GetFileNameWithoutExtension(FullPath).ToLower();
    bool isRunning = false;

    Process[] pList = Process.GetProcessesByName(FileName);

    foreach (Process p in pList) {
        if (p.MainModule.FileName.StartsWith(FilePath, StringComparison.InvariantCultureIgnoreCase))
        {
            isRunning = true;
            break;
        }
    }

    return isRunning;
}

e usarlo come:

ProgramIsRunning(@"c:\loc1\test.exe");

provare questo ... Io lo uso per determinare all'avvio se un altro processo è già in esecuzione con lo stesso nome del file exe che sto cercando di iniziare, e poi basta portare quello di primo piano, (e per mettere a fuoco) se è già in esecuzione ... si potrebbe modificare per fare un nome di processo e di prova per quel nome specifico ... Questo vi dirà se c'è un processo in esecuzione con un certo nome, ma non dove questo processo è stato caricato da .. .

Se c'è un processo in esecuzione con il nome specificato, quindi se questo processo ha avuto un metodo accessibile a vista che restituisce in cui è stato caricato da, si potrebbe chiamare quel metodo sul processo in esecuzione, in caso contrario, non lo so ..

Ma solo per curiosità, perché ti importa, a meno che siano diversi? E se sono diversi, in qualche modo, il codice per utilizzare tale differenza (qualunque esso sia) per rilevare che è caricato. Ma se sono lo stesso come può importa che su disco immagine è stata usata per caricarlo?

    [DllImport("user32.dll")]
    private static extern bool SetForegroundWindow(IntPtr hWnd);
    [DllImport("user32.dll")]
    private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
    [DllImport("user32.dll")]
    private static extern bool IsIconic(IntPtr hWnd);

    private const int SW_HIDE = 0;
    private const int SW_SHOWNORMAL = 1;
    private const int SW_SHOWMINIMIZED = 2;
    private const int SW_SHOWMAXIMIZED = 3;
    private const int SW_SHOWNOACTIVATE = 4;
    private const int SW_RESTORE = 9;
    private const int SW_SHOWDEFAULT = 10;

 private static bool IsAlreadyRunning()
    {
        // get all processes by Current Process name
        Process[] processes = 
            Process.GetProcessesByName(
                Process.GetCurrentProcess().ProcessName);

        // if there is more than one process...
        if (processes.Length > 1) 
        {
            // if other process id is OUR process ID...
            // then the other process is at index 1
            // otherwise other process is at index 0
            int n = (processes[0].Id == Process.GetCurrentProcess().Id) ? 1 : 0;

            // get the window handle
            IntPtr hWnd = processes[n].MainWindowHandle;

            // if iconic, we need to restore the window
            if (IsIconic(hWnd)) ShowWindowAsync(hWnd, SW_RESTORE);

            // Bring it to the foreground
            SetForegroundWindow(hWnd);
            return true;
        }
        return false;
    }

Si dovrebbe iterare su tutti i processi esistenti e quindi controllare le loro proprietà MainModule per il nome del file che si sta cercando. Qualcosa di simile a questo

using System.Diagnostics;
using System.IO;

//...

string fileNameToFilter = Path.GetFullPath("c:\\loc1\\test.exe");

foreach (Process p in Process.GetProcesses())
{
   string fileName = Path.GetFullPath(p.MainModule.FileName);

   //cehck for equality (case insensitive)
   if (string.Compare(fileNameToFilter, fileName, true) == 0)
   {
      //matching...
   }
}

Questa funzione può aiutare:

using System.Diagnostics;

public bool IsProcessOpen(string name)
{
    foreach (Process clsProcess in Process.GetProcesses()) {
        if (clsProcess.ProcessName.Contains(name))
        {
            return true;
        }
    }
    return false;
} 

Fonte: http://www.dreamincode.net/code/snippet1541.htm

Qualcosa di simile. GetMainModuleFileName aiuta ad accedere processo x64 da 86.

  [DllImport("kernel32.dll")]
  public static extern bool QueryFullProcessImageName(IntPtr hprocess, int dwFlags, StringBuilder lpExeName, out int size);

  private bool CheckRunningProcess(string processName, string path) {

  Process[] processes = Process.GetProcessesByName(processName);
  foreach(Process p in processes) {
    var name = GetMainModuleFileName(p);
    if (name == null)
      continue;
    if (string.Equals(name, path, StringComparison.InvariantCultureIgnoreCase)) {
      return true;
    }
  }
  return false;
}

// Get x64 process module name from x86 process
private static string GetMainModuleFileName(Process process, int buffer = 1024) {

  var fileNameBuilder = new StringBuilder(buffer);
  int bufferLength = fileNameBuilder.Capacity + 1;
  return QueryFullProcessImageName(process.Handle, 0, fileNameBuilder, out bufferLength) ?
      fileNameBuilder.ToString() :
      null;
}

È possibile utilizzare un nome mutex , che è chiamato fuori della struttura di directory il programma è in esecuzione in.

System.Reflection.Assembly.GetEntryAssembly()

Si aprirà per voi un sacco di informazioni circa l'assemblaggio di entrata, come ad esempio:

System.Reflection.Assembly.GetEntryAssembly().CodeBase;

Questo dirà la posizione del gruppo di esecuzione.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top