1

i try execute command to CMD, but it don't work Includes:

#include <Windows.h>
#include <processthreadsapi.h>
#include <shellapi.h>
#include <stdio.h>
#include <iostream>

How i try open notepad:

ShellExecute(NULL, (LPCWSTR)"open", (LPCWSTR)"cmd", (LPCWSTR)"/c notepad.exe", NULL, SW_NORMAL);
  • can you explain about your cast? i mean `LPCWSTR`. – MH Alikhani Jul 25 '20 at 13:19
  • 2
    Explicit casts are generally not the way to fix compiler errors about wrong types. Sure, your code will compile, but likely will not work. – interjay Jul 25 '20 at 13:21
  • Also, a command line has to include the program name. In this it will think `/c` is the program name and won't work because the `/c` is then missing as actual parameter. You can pass `NULL` instead of the application (or keep it as `cmd`) and then use `cmd /c notepad.exe` as command line. However, I don't understand why you want to involve CMD at all - just run `notepad.exe` directly. – CherryDT Jul 25 '20 at 13:22
  • I think your function `ShellExecute` could not get `wchar_t*` instead of `char*` or null terminated string. cast to somthing correct ( char* or do nothing) and it will works – MH Alikhani Jul 25 '20 at 13:25
  • 3
    One bug is here `(LPCWSTR)"/c notepad.exe"` when you have to cast a string type you are almost always doing the wrong thing. Use `L"/c notepad.exe"` instead. Related: [https://stackoverflow.com/questions/1810343/is-a-wide-character-string-literal-starting-with-l-like-lhello-world-guarantee](https://stackoverflow.com/questions/1810343/is-a-wide-character-string-literal-starting-with-l-like-lhello-world-guarantee) – drescherjm Jul 25 '20 at 13:29
  • Thanks for your helping all, i set project charset to "use multi byte character set" and it work without LPCWSTR – Lexa Berezin Jul 25 '20 at 13:43

1 Answers1

2

This works

ShellExecute(NULL, L"open", L"cmd", L"/c notepad.exe", NULL, SW_NORMAL);

Don't use casts to remove compiler errors. The errors are telling you that you are using the wrong types, use the right types instead.

john
  • 85,011
  • 4
  • 57
  • 81