7

I have this code:

ShellExecute(Handle, 'open',
             'C:\Users\user\Desktop\sample\menu\WTSHELP\start.html',
             nil, nil, sw_Show);

How can I replace the literal in the third argument with a string variable? If I use code like below it doesn't compile.

var
  dir: string;

dir := 'C:\Users\user\Desktop\sample\menu\WTSHELP\start.html';
ShellExecute(Handle, 'open', dir, nil, nil, sw_Show);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user1884060
  • 75
  • 1
  • 7
  • 2
    Make sure that when you post your question, you include as much information as possible. Here, you should have told us how 'dir' is declared. The answers below make an assumption about the type. – Nick Hodges Apr 02 '13 at 21:06
  • 1
    Yes, and although I know the issue (which is answered below), the point is you should always tell us what the error message is (in this case a mis-match between String and PChar). – Jerry Dodge Apr 02 '13 at 21:33

2 Answers2

9

I assume that dir is of type string. Then

ShellExecute(Handle, 'open', PChar(dir), nil, nil, SW_SHOWNORMAL);

should work. Indeed, the compiler tells you this; it says something like

[DCC Error] Unit1.pas(27): E2010 Incompatible types: 'string' and 'PWideChar'

(Also notice that you normally use SW_SHOWNORMAL when you call ShellExecute.)

Andreas Rejbrand
  • 105,602
  • 8
  • 282
  • 384
  • 1
    And another possibility is `@dir[1]` – OnTheFly Apr 02 '13 at 22:08
  • When it tells you, `PWideChar`, shouldn't you use PWideChar instead of `PChar`? There are still some D2007 or lower users here :) – Sebastian Apr 03 '13 at 13:59
  • 5
    @SebastianGodelet: No, that's exactly why you should *not* use `PWideChar`. In Delphi >= 2009, `PChar` means exactly `PWideChar`. So the OP, using Delphi 2010, would get the error message stated above, and in principle can use any of the two options. But if you use Delphi < 2009, then `ShellExecute` as defined in `Windows.pas` will refer to `ShellExecuteA` in `Shell32.dll`, and so it would expect the non-Unicode `PChar` (which is `PAnsiChar`). Hence, in *both* cases, `PChar` works. If you use `PWideChar`, it will only work in Delphi >= 2009. – Andreas Rejbrand Apr 03 '13 at 15:59
  • Oh yes shure I got it backwards. So if I wanted to use Unicode, I would have to write my own `extern` declaration using the `W` Suffix, right? – Sebastian Apr 03 '13 at 17:41
  • @user that fails for the empty strong. You need to use the PChar cast. – David Heffernan Apr 04 '13 at 00:04
7

ShellExecute is a Windows API. Thus, you need to pass the PChar type to it.

If I assume correctly that your dir variable is a string, then you can cast the string to be a PChar, and call ShellExecute as follows:

ShellExecute(Handle,'open', PChar(dir) ,nil,nil,sw_Show);
Nick Hodges
  • 16,902
  • 11
  • 68
  • 130