2

I want to open MS Word docs from my app. I use ShellExecute function to do the job. It does open a word doc that I specified, but it restored a doc that I opened before and minimised, that is not what I want. Also the ShellExecute returns 42 that I don't know the meaning. Does I used the ShellExecute incorrectly?

using System;
using System.Windows.Forms;

namespace Test_Doc
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        [System.Runtime.InteropServices.DllImport("Shell32.dll")]
        public static extern int ShellExecute(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirecotry, int nShowCmd);

        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 void button1_Click(object sender, EventArgs e)
        {
            string filePath = System.Reflection.Assembly.GetEntryAssembly().Location;
            string fileName = System.IO.Path.Combine(filePath, "2.docx");
            int i = ShellExecute(this.Handle, "Edit", fileName, null, null, SW_SHOWNORMAL);
            MessageBox.Show(i.ToString());
        }
    }
}

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
peter
  • 1,009
  • 3
  • 15
  • 23
  • This is "intended behaivour" by Word (all office products) and not `ShellExecute`, open a word file and minimise it, now manually open another word file and lo and behold the first one un-minimises itself. It's something that's been bugging me personally for quite a while now but it is for all I can tell intended behaivour. – MindSwipe Oct 17 '22 at 06:45
  • What is the benefit of using `ShellExecute` over Office automation? Do you have any arguments for that specifically? – Eugene Astafiev Oct 17 '22 at 11:47
  • Our app is written with Delphi 6. Delphi 6 does not support Office automation well. for example, if I use ole to open a word doc, it is minimised. So, what I may do is creating a office automation in C# and make it as a dll for the Delphi app. – peter Oct 20 '22 at 00:05

1 Answers1

0

ShellExecute doesn't let you control the application. However, you may automate Word from a C# application where you could manage the application afterwards. For example, see How to automate Microsoft Word to create a new document by using Visual C# for more information.

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
  • Thanks. Do you mean no matter how many docs I open, it just one word app behind, so ShellExecute calls the word app and opens one doc and show all docs that were already opened? – peter Oct 18 '22 at 04:37
  • You can't control the Word app with `ShellExecute`. – Eugene Astafiev Oct 18 '22 at 14:09