startup_task_win.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. This file is part of Telegram Desktop,
  3. the official desktop application for the Telegram messaging service.
  4. For license and copyright information please follow this link:
  5. https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
  6. */
  7. #include <windows.h>
  8. #include <shellapi.h>
  9. #include <array>
  10. #include <string>
  11. using namespace std;
  12. constexpr auto kMaxPathLong = 32767;
  13. [[nodiscard]] std::wstring ExecutableDirectory() {
  14. auto exePath = std::array<WCHAR, kMaxPathLong + 1>{ 0 };
  15. const auto exeLength = GetModuleFileName(
  16. nullptr,
  17. exePath.data(),
  18. kMaxPathLong + 1);
  19. if (!exeLength || exeLength >= kMaxPathLong + 1) {
  20. return {};
  21. }
  22. const auto exe = std::wstring(exePath.data());
  23. const auto last1 = exe.find_last_of('\\');
  24. const auto last2 = exe.find_last_of('/');
  25. const auto last = std::max(
  26. (last1 == std::wstring::npos) ? -1 : int(last1),
  27. (last2 == std::wstring::npos) ? -1 : int(last2));
  28. if (last < 0) {
  29. return {};
  30. }
  31. return exe.substr(0, last);
  32. }
  33. int APIENTRY wWinMain(
  34. HINSTANCE instance,
  35. HINSTANCE prevInstance,
  36. LPWSTR cmdParamarg,
  37. int cmdShow) {
  38. const auto directory = ExecutableDirectory();
  39. if (!directory.empty()) {
  40. ShellExecute(
  41. nullptr,
  42. nullptr,
  43. (directory + L"\\Telegram.exe").c_str(),
  44. L"-autostart",
  45. directory.data(),
  46. SW_SHOWNORMAL);
  47. }
  48. return 0;
  49. }