وبلاگ جدید علیرضا شهامت در زمستان 1401

وبلاگ جدید علیرضا شهامت در زمستان 1401

به نام خدا - سلام - به وبلاگ جدید علیرضا شهامت خوش آمدید! بنده این وبلاگ را در تاریخ 1401/10/28 تأسیس کرده ام.
وبلاگ جدید علیرضا شهامت در زمستان 1401

وبلاگ جدید علیرضا شهامت در زمستان 1401

به نام خدا - سلام - به وبلاگ جدید علیرضا شهامت خوش آمدید! بنده این وبلاگ را در تاریخ 1401/10/28 تأسیس کرده ام.

برنامه ی ریستارت کردن کامپیوتر - راه اندازی مجدد پی سی - Restart the PC

برنامه ی ریستارت کردن کامپیوتر - راه اندازی مجدد پی سی - Restart the PC


به نام خدا

سلام دوستان

اول مطلب یادداشت قبلی را بی زحمت بخونید.

((لینک یادداشت قبلی))

https://lrsh140110.blogsky.com/1403/03/26

https://lrsh140110.blogsky.com/1403/03/26/page/2



نکات ضروری قبل از دانلود و نصب برنامه:

نکات ضروری قبل از دانلود و نصب برنامه

https://lrsh140110.blogsky.com/1403/02/22/post-19/Necessary-explanations-for-downloading-and-using-programs-07-11-1402



لینک دانلود برنامه ی ریستارت:

متاسفانه سایت بلاگ اسکای، اجازه ی انتشار چنین فایلی را نمی دهد.

شاید اجازه ی نوشتن کدهایش را بدهد.


تصاویر برنامه:

جدول تصاویر:

متاسفانه مشکلی در سایت پیکوفایل به وجود آمده!
لطفا چند هفته صبر کنید...




کدهای برنامه:

جدول کدها:

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace Restart_PC
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}
namespace Restart_PC
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.button_Restart_the_PC = new System.Windows.Forms.Button();
            this.button_Shut_down_the_PC = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // button_Restart_the_PC
            //
            this.button_Restart_the_PC.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(255)))));
            this.button_Restart_the_PC.Font = new System.Drawing.Font("Microsoft Sans Serif", 23F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.button_Restart_the_PC.Location = new System.Drawing.Point(32, 38);
            this.button_Restart_the_PC.Name = "button_Restart_the_PC";
            this.button_Restart_the_PC.Size = new System.Drawing.Size(274, 124);
            this.button_Restart_the_PC.TabIndex = 0;
            this.button_Restart_the_PC.Text = "Restart the PC";
            this.button_Restart_the_PC.UseVisualStyleBackColor = false;
            this.button_Restart_the_PC.Click += new System.EventHandler(this.button_Restart_the_PC_Click);
            //
            // button_Shut_down_the_PC
            //
            this.button_Shut_down_the_PC.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(255)))));
            this.button_Shut_down_the_PC.Font = new System.Drawing.Font("Microsoft Sans Serif", 23F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.button_Shut_down_the_PC.Location = new System.Drawing.Point(186, 212);
            this.button_Shut_down_the_PC.Name = "button_Shut_down_the_PC";
            this.button_Shut_down_the_PC.Size = new System.Drawing.Size(358, 124);
            this.button_Shut_down_the_PC.TabIndex = 0;
            this.button_Shut_down_the_PC.Text = "Shut down the PC";
            this.button_Shut_down_the_PC.UseVisualStyleBackColor = false;
            this.button_Shut_down_the_PC.Click += new System.EventHandler(this.button_Shut_down_the_PC_Click);
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(24)))), ((int)(((byte)(92)))), ((int)(((byte)(220)))));
            this.ClientSize = new System.Drawing.Size(692, 404);
            this.Controls.Add(this.button_Shut_down_the_PC);
            this.Controls.Add(this.button_Restart_the_PC);
            this.Name = "Form1";
            this.Text = "Restart the PC";
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Button button_Restart_the_PC;
        private System.Windows.Forms.Button button_Shut_down_the_PC;
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

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

        private void button1_Click(object sender, EventArgs e)
        {





        }

        private void button_Restart_the_PC_Click(object sender, EventArgs e)
        {


            Question_for_restarting();


        }

        private void Question_for_restarting()
        {
            //Restart_the_PC();



            //MessageBox.Show(
            //    string,
            //string,
            //        System.Windows.Forms.MessageBoxButtons,
            //System.Windows.Forms.MessageBoxIcon,
            //System.Windows.Forms.MessageBoxDefaultButton,
            //System.Windows.Forms.MessageBoxOptions
            //)


            DialogResult a =
                MessageBox.Show(
                this,
                "آیا می خواهید رایانه ی خود را راه اندازی مجدد نمایید؟" +
                "\n" +
                "لطفاً قبل از راه اندازی مجدد، تمام کارهای خود را ذخیره کنید." +
                "\n" +
                "Do you want to Restart your PC? " +
                "\n" +
                "(Please save all of your works before restarting.)",
                "Do you want to Restart?",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question,
                MessageBoxDefaultButton.Button2,
                MessageBoxOptions.RtlReading |
                MessageBoxOptions.RightAlign
                );




            if (a == DialogResult.Yes)
            {

                Restart_the_PC();
            }

        }

        private static void Restart_the_PC()
        {
            System.Diagnostics.Process.Start("shutdown.exe", "-r -t 0");
        }

        private void button_Shut_down_the_PC_Click(object sender, EventArgs e)
        {
            Question_for_shutting_down();
        }

        private void Question_for_shutting_down()
        {
            //throw new Exception("The method or operation is not implemented.");



            DialogResult b =
              MessageBox.Show(
              this,
              "آیا می خواهید رایانه ی خود را خاموش نمایید؟" +
              "\n" +
              "لطفاً قبل از خاموش کردن، تمام کارهای خود را ذخیره کنید." +
              "\n" +
              "Do you want to shut down your PC? " +
              "\n" +
              "(Please save all of your works before shutting down.)",
              "Do you want to shut down?",
              MessageBoxButtons.YesNo,
              MessageBoxIcon.Question,
              MessageBoxDefaultButton.Button2,
              MessageBoxOptions.RtlReading |
              MessageBoxOptions.RightAlign
              );




            if (b == DialogResult.Yes)
            {

                Shut_down_the_PC();
            }


        }

        private void Shut_down_the_PC()
        {
            //throw new Exception("The method or operation is not implemented.");


            //System.Diagnostics.Process.Start("shutdown.exe", "-r -t 0");

            System.Diagnostics.Process.Start("shutdown.exe", "/s /t 0");


        }
    }
}


//  comments:

//  URL = "https://stackoverflow.com/questions/1215139/reboot-machine-from-a-c-wpf-app";

//sources:

/*  

 *
site logo

Skip to main content
Stack Overflow

    About
    Products
    OverflowAI

2024 Developer survey is here and we would like to hear from you!

Home
Questions
Tags
Users
Companies
Labs
Jobs
Discussions
Collectives

    Communities for your favorite technologies. Explore all Collectives

Teams

Ask questions, find answers and collaborate at work with Stack Overflow for Teams.

Reboot machine from a C#/WPF app
Asked 14 years, 10 months ago
Modified 3 years, 11 months ago
Viewed 50k times
42

I want to have a button in my WPF app that restarts the machine. This app is always running on Vista.

The fact that a quick search hasn't turned anything up makes me think this might be harder than I wish it was... any ideas? Thanks!

    c#.netwindowsreboot

Share
Improve this question
Follow
edited Jan 21, 2013 at 23:37
abatishchev's user avatar
abatishchev
99.5k8888 gold badges300300 silver badges438438 bronze badges
asked Jul 31, 2009 at 22:15
Josh Santangelo's user avatar
Josh Santangelo
94644 gold badges1111 silver badges1616 bronze badges
Add a comment
4 Answers
Sorted by:
81

Try this:

System.Diagnostics.Process.Start("shutdown.exe", "-r -t 0");

This starts Windows' inbuilt shutdown tool, which can also shut down or logoff a remote or the local machine.

Here is the list of full options from ss64.com:

Syntax

      SHUTDOWN [logoff_option]  [/m \\Computer] [options]

logoff_option:
    /i         Display the GUI (must be the first option)
    /l         Log off. This cannot be used with /m or /d option
    /s         Shutdown
    /r         Shutdown and Restart
    /a         Abort a system shutdown.
               (only during the time-out period)
    /p         Turn off the local computer with no time-out or warning
               (only with /d)
    /h         Hibernate the local computer (only with /f )
    /e         Document the reason for an unexpected shutdown of a computer

Options:

   /m \\Computer  : A remote computer to shutdown.

   /t:xxx         : Time until system shutdown in seconds.
                    The valid range is xxx=0-600 seconds. [default=30]
   /c "Msg"       : An optional shutdown message [Max 127 chars]

   /f             : Force running applications to close.
                    This will not prompt for File-Save in any open applications.
                    so will result in a loss of all unsaved data!!!

   /d u:xx:yy     : List a USER reason code for the shutdown.
   /d P:xx:yy     : List a PLANNED reason code for the shutdown.
                     xx Specifies the major reason code (0-255)
                     yy Specifies the minor reason code (0-65536)

You'll probably notice that I have used the Linux/UNIX style of passing command-line arguments (using the '-') sign. On Windows, the convention is using '/'. This doesn't matter - the program doesn't care.
Share
Improve this answer
Follow
answered Jul 31, 2009 at 22:16
Lucas Jones's user avatar
Lucas Jones
20k88 gold badges7676 silver badges8888 bronze badges

    3
    this is more useful for both windows and linux –
    dexiang
    Commented Apr 13, 2018 at 7:49

Add a comment
23

You can use the ExitWindowsEx API. From pinvoke.net

[Flags]
public enum ExitWindows : uint
{
   // ONE of the following five:
   LogOff = 0x00,
   ShutDown = 0x01,
   Reboot = 0x02,
   PowerOff = 0x08,
   RestartApps = 0x40,
   // plus AT MOST ONE of the following two:
   Force = 0x04,
   ForceIfHung = 0x10,
}

[Flags]
enum ShutdownReason : uint
{
    MajorApplication = 0x00040000,
    MajorHardware = 0x00010000,
    MajorLegacyApi = 0x00070000,
    MajorOperatingSystem = 0x00020000,
    MajorOther = 0x00000000,
    MajorPower = 0x00060000,
    MajorSoftware = 0x00030000,
    MajorSystem = 0x00050000,

    MinorBlueScreen = 0x0000000F,
    MinorCordUnplugged = 0x0000000b,
    MinorDisk = 0x00000007,
    MinorEnvironment = 0x0000000c,
    MinorHardwareDriver = 0x0000000d,
    MinorHotfix = 0x00000011,
    MinorHung = 0x00000005,
    MinorInstallation = 0x00000002,
    MinorMaintenance = 0x00000001,
    MinorMMC = 0x00000019,
    MinorNetworkConnectivity = 0x00000014,
    MinorNetworkCard = 0x00000009,
    MinorOther = 0x00000000,
    MinorOtherDriver = 0x0000000e,
    MinorPowerSupply = 0x0000000a,
    MinorProcessor = 0x00000008,
    MinorReconfig = 0x00000004,
    MinorSecurity = 0x00000013,
    MinorSecurityFix = 0x00000012,
    MinorSecurityFixUninstall = 0x00000018,
    MinorServicePack = 0x00000010,
    MinorServicePackUninstall = 0x00000016,
    MinorTermSrv = 0x00000020,
    MinorUnstable = 0x00000006,
    MinorUpgrade = 0x00000003,
    MinorWMI = 0x00000015,

    FlagUserDefined = 0x40000000,
    FlagPlanned = 0x80000000
}

[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool ExitWindowsEx(ExitWindows uFlags, ShutdownReason dwReason);

And to use it:

ExitWindowsEx(
  ExitWindows.Reboot,
  ShutdownReason.MajorOther | ShutdownReason.MinorOther | ShutdownReason.FlagPlanned
);

Share
Improve this answer
Follow
edited Jan 20, 2014 at 6:19
answered Jul 31, 2009 at 22:40
Martin Liversage's user avatar
Martin Liversage
106k2222 gold badges212212 silver badges260260 bronze badges

    9
    This won't work unless you also adjust the process token to get shutdown privileges. See ithoughthecamewithyou.com/post/Reboot-computer-in-C-NET.aspx for a class that does this properly. –
    Robert Ellison
    Commented Sep 11, 2010 at 18:30
    It works for me without setting any process token. WPF app with UAC enabled, Win7 x64. –
    RandomEngy
    Commented Jul 21, 2011 at 6:42
    1
    You want to pass the second parameter to ExitWindowsEx like this: ShutdownReason.MajorOther | ShutdownReason.MinorOther | ShutdownReason.FlagPlanned. Using the bitwise AND will just zero the argument out. The system will be left with the report of an unplanned and unspecified shutdown in the Shutdown Event Tracker. Read more here: msdn.microsoft.com/en-us/library/windows/desktop/… –
    Derek W
    Commented Jan 20, 2014 at 3:51
    1
    @DerekW: Thanks for pointing out the typo and suggesting FlagPlanned. I have edited the answer to incorporate your suggestions. –
    Martin Liversage
    Commented Jan 20, 2014 at 6:22
    1
    @RobertEllison It does work as Administrator on Windows 7, but no longer on Windows 10 which I have now seen. Error 1314. –
    ygoe
    Commented Aug 12, 2016 at 19:14

Show 1 more comment
10

An alternative would be to use WMI (i.e. the System.Management namespace); Google brings up variations on this code --

  ManagementClass W32_OS = new ManagementClass("Win32_OperatingSystem")
  ManagementBaseObject inParams, outParams;
  int result;
  W32_OS.Scope.Options.EnablePrivileges = true;

  foreach(ManagementObject obj in W32_OS.GetInstances())
  {
    inParams = obj.GetMethodParameters("Win32Shutdown");
    inParams["Flags"] = 6; //ForcedReboot; -- fixed to restart rather than shutdown
    inParams["Reserved"] = 0;

    outParams = obj.InvokeMethod("Win32Shutdown", inParams, null)
    result = Convert.ToInt32(outParams["returnValue"]);
    if (result !=0) throw new Win32Exception(result);
  }

Share
Improve this answer
Follow
edited Jul 31, 2009 at 23:01
answered Jul 31, 2009 at 22:33
Steve Gilham's user avatar
Steve Gilham
11.3k33 gold badges3232 silver badges3737 bronze badges
Add a comment
1

Working code inside a windows service:

var cmd = new System.Diagnostics.ProcessStartInfo("shutdown.exe", "-r -t 0");
cmd.CreateNoWindow = true;
cmd.UseShellExecute = false;
cmd.ErrorDialog = false;
System.Diagnostics.Process.Start(cmd);

Share
Improve this answer
Follow
answered Jun 25, 2020 at 5:14
iojancode's user avatar
iojancode
61866 silver badges77 bronze badges
Add a comment
Your Answer

Sign up or log in
Post as a guest
Name
Email

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.
Not the answer you're looking for? Browse other questions tagged

    c#.netwindowsreboot

or ask your own question.

    Featured on Meta
    Upcoming sign-up experiments related to tags
    Policy: Generative AI (e.g., ChatGPT) is banned
    The return of Staging Ground to Stack Overflow
    The 2024 Developer Survey Is Live

Linked
3
What is the equivalent of an IISReset if I want to use Microsoft.Web.Administration
1
Reboot machine from C#/Forms App while session is locked
0
How to force reboot Windows 7 from inside a C# Windows Service
Related
22
Restarting Windows from within a .NET application
0
C# code that initiates a self reboot?
31
Restart application using C#
11
Restart computer from WinForms app?
3
Shutdown or Reboot local machine on Button
1
Shutdown or Restart Machine In C# and ASP.NET
0
Resuming a C# application after system restart
1
Reboot machine from C#/Forms App while session is locked
0
Reboot Windows from within a service
2
WPF application restart
Hot Network Questions

    TCP source port sharing
    Okular window not opening
    What was God's original plan for humanity prior to the fall?
    Unpaired socks in my lap
    Plant identification, please
    Does generating function always have a convergence domain?
    What is the time-travel story where "ugly chickens" are trapped in the past and brought to the present to become ingredients for a soup?
    Who was the first philosopher to describe approximation?
    Can I remove an appimage file?
    Aligning surveyed point layers in QGIS
    I buy retrocomputing devices, but they set my allergies off. Any advice on sanitizing new acquisitions?
    Unsure whether to begin a PhD program
    What is the goal of the message “astronaut use only” written on one Hubble's module?
    How would I fix this leaking garage?
    Definability properties of box-open subsets of Polish space
    Is there a way knowledge checks can be done without an Intelligence trait?
    What is the meaning of 多岁 in 在中国,60多岁已经是退休的年纪了?
    The smell of wet gypsum
    Maximum Power Transfer Theorem Question
    Why was the 1540 a computer in its own right?
    Why isn't "meanwhile" advisable in this sentence? Doesn't it mean "at the same time"?
    Why is MSS important? Why can't we just rely on the MTU?
    Would a series of gravitational waves from a supernova affect time on a 200 year old clock just as water waves affected clocks on ships in rough seas?
    Schengen visa issued by Germany - Is a layover in Vienna okay before heading to Berlin?

Question feed

Stack Overflow

    Questions
    Help

Products

    Teams
    Advertising
    Collectives
    Talent

Company

    About
    Press
    Work Here
    Legal
    Privacy Policy
    Terms of Service
    Contact Us
    Cookie Settings
    Cookie Policy

Stack Exchange Network

    Technology
    Culture & recreation
    Life & arts
    Science
    Professional
    Business
    API
    Data

    Blog
    Facebook
    Twitter
    LinkedIn
    Instagram

Site design / logo © 2024 Stack Exchange Inc; user contributions licensed under CC BY-SA. rev 2024.6.14.10983

 *
 *
*/


امیدوار باشید!

خدانگهدار




نظرات 0 + ارسال نظر
برای نمایش آواتار خود در این وبلاگ در سایت Gravatar.com ثبت نام کنید. (راهنما)
ایمیل شما بعد از ثبت نمایش داده نخواهد شد