I am doing an application in c# and in my application I am opening some exe file like MS word, calculator so when I open the application and then I hide it I would like to create a sort of shortcut in the app so that when I click on the shortcut the window will open again.

What I have tried:

What I did is that I was able to put the window of the exe file on topMost but when it is hidden or resized I would like to create a shortcut in the application on C# so that when I click on the shortcut the exe file will reopen.
Here is the code that I tried to restore.

using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Test
{
    class ResizeApp
    {
        public static IntPtr wdwIntPtr;

        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(string className, string windowTitle);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool ShowWindow(IntPtr hWnd, ShowWindowEnum flags);

        [DllImport("user32.dll")]
        private static extern int SetForegroundWindow(IntPtr hwnd);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool GetWindowPlacement(IntPtr hWnd, ref Windowplacement lpwndpl);

        private enum ShowWindowEnum
        {
            Hide = 0,
            ShowNormal = 1, ShowMinimized = 2, ShowMaximized = 3,
            Maximize = 3, ShowNormalNoActivate = 4, Show = 5,
            Minimize = 6, ShowMinNoActivate = 7, ShowNoActivate = 8,
            Restore = 9, ShowDefault = 10, ForceMinimized = 11
        };

        private struct Windowplacement
        {
            public int length;
            public int flags;
            public int showCmd;
            public System.Drawing.Point ptMinPosition;
            public System.Drawing.Point ptMaxPosition;
            public System.Drawing.Rectangle rcNormalPosition;
        }

        public ResizeApp()
        {

        }

        public static void BringWindowToFront(string processName, FlowLayoutPanel PIC_Barre,Timer tim)
        {
            tim.Start();
            var processes = Process.GetProcessesByName(processName);
            if (processes.Any()) //a copy is already running
            {
                //I can't currently tell the window's state,
                //so I both restore and activate it
                var handle = processes.First().MainWindowHandle;
                ShowWindow(handle, ShowWindowEnum.Restore); //GRR!!!
                SetForegroundWindow(handle);

            wdwIntPtr = FindWindow(null, processName);

            //get the hWnd of the process
            Windowplacement placement = new Windowplacement();
            GetWindowPlacement(wdwIntPtr, ref placement);

            // Check if window is minimized
            if (placement.showCmd == 2)
            {
                Button btn = new Button();
                btn.Width = 20;
                btn.Height = 20;
                PIC_Barre.Controls.Add(btn);
                btn.Click += button1_Click;

                //the window is hidden so we restore it

            }

            //set user's focus to the window
            SetForegroundWindow(wdwIntPtr);
            }

        }
        private static void button1_Click(object sender, EventArgs e)
        { ShowWindow(wdwIntPtr, ShowWindowEnum.Restore); }

    }
}

Thank you.

Dani AI

Generated

— a reliable pattern is: (1) find or keep the Process object you started, (2) obtain the real top-level window handle for that process, (3) restore it if minimized, and (4) force it to the foreground. is correct to flag the WindowPlacement/showCmd issue: when you call native GetWindowPlacement you must initialize the structure length (Marshal.SizeOf) before the call; otherwise the results are not trustworthy. Also avoid using FindWindow with a process name — FindWindow expects a window class or a window title.

Practical steps (robust):

  • If you start the app, keep the Process returned by Process.Start and call WaitForInputIdle, then poll Process.MainWindowHandle until non-zero.
  • If you must find an already-running process, enumerate top-level windows and match by process id (EnumWindows + GetWindowThreadProcessId) rather than guessing by process name.
  • Detect minimized state with IsIconic and restore with ShowWindowAsync(SW_RESTORE).
  • To overcome Windows foreground restrictions, attach your thread to the target window thread, restore/bring-to-top, then detach — this reliably gives focus.

Example: force-foreground helper (core idea — P/Invoke declarations omitted here for brevity):

void ForceForeground(IntPtr hWnd)
{
  uint targetThread = GetWindowThreadProcessId(hWnd, out _);
  uint currentThread = GetCurrentThreadId();
  AttachThreadInput(currentThread, targetThread, true);
  ShowWindowAsync(hWnd, SW_RESTORE);
  BringWindowToTop(hWnd);
  SetForegroundWindow(hWnd);
  AttachThreadInput(currentThread, targetThread, false);
}

Note for Office apps: rather than window hacks, use COM interop when possible — e.g. Marshal.GetActiveObject("Word.Application") to set Visible = true and WindowState = Normal. Troubleshooting: elevated vs non‑elevated processes, apps that minimize to tray (no top-level window), and processes on another desktop/session will block these techniques — handle those cases by starting a new process or using app-specific automation.

Recommended Answers

All 2 Replies

Using the word "shortcut" instead of "button" seems confusing. I believe you want to create a button to include in your Windows form, and build in the function of showing a previously hidden window once clicked. Your code seems like a snippet of your complete work.

Your showCmdof struct WindowPlacementis not initialized, so I'm wondering how you can make such comparison if (placement.showCmd == 2)?
Why is the button function inside class ResizeApp?

Your app code should be simple. First, maybe gather Window titles instead of process names to make it easier. I don't want to re-design the whole UI for you since I don't know what you're trying to make your app look, so I'll see what your next reply is.

Is there a special reason why you want to manipulate applications from your application that way? I'd use W10 for that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.