0

I have a button with a command that need to open a file in Notepad and I have the folowing code:

Process.Start("notepad.exe", path);

This is working, but when I press the button second time, I dont need to open the file again, I want to bring it in focus, to be the active window.

EDIT I can open diferent files in notepad, but when I press again the button it need to bring in focus the notepad with the correct name.

How can I do this?

Sipick
  • 71
  • 6
  • https://stackoverflow.com/questions/2315561/correct-way-in-net-to-switch-the-focus-to-another-application – jewishmoses Jul 02 '20 at 13:07
  • 1
    The problem is, even if you track the window you opened and refocus it, the user could, for all you know, have opened a completely different/irrelevant file into that instance by now. It's probably safer to open a fresh instance so that you know it's actually showing what your program wants it to show. – Damien_The_Unbeliever Jul 02 '20 at 13:12
  • @Damien_The_Unbeliever the client want this, he need to open a lot of files in notepad and if one is already opened, he wants to bring it in focus, not to open again – Sipick Jul 02 '20 at 13:30
  • @jewishmoses it kinda answer, but not completly, this will work for only 1 notepad, I need to do this for every opened noted, but which have diferent name – Sipick Jul 02 '20 at 13:35
  • @jewishmoses I have used the solution from your link and I got the process by title and it is working – Sipick Jul 02 '20 at 14:01
  • @Sipick this sound like an XY problem. The user says he wants notepad integration, but he probably needs something else, like an easy way to edit the data in text files, and that can be done in many different ways. – JonasH Jul 02 '20 at 14:03

1 Answers1

0

Try this

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    static extern bool SetForegroundWindow(IntPtr hWnd);
    public static void OpenProcess()
    {
        var process = new Process();
        if (Process.GetProcessesByName("notepad").Any(f => f.MainWindowTitle.Contains(@"name.txt")))
        {
            process = Process.GetProcessesByName("notepad").FirstOrDefault(f => f.MainWindowTitle.Contains("name.txt"));
            SetForegroundWindow(process.MainWindowHandle);
            return;
        }
        Process.Start(@"notepad.exe", @"D:\...\name.txt");
    }
IlBiff
  • 1
  • 1