在form1构造函数中调用它时,我应该给方法Args什么参数?

时间:2016-03-16 23:05:10

标签: c# .net winforms

我记得/认为它应该是一种字符串数组但不确定我该怎么做以及如何做。 在最初的Args是在Program.cs中,但我把它移动到Form1。 我知道它之前对我有用,但不确定Args应该得到什么args。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.IO;

namespace ShellContextMenu
{
    public partial class Form1 : Form
    {
        // file type to register
        const string FileType = "jpegfile";

        // context menu name in the registry
        const string KeyName = "Simple Context Menu";
        const string KeyName1 = "Simple Context Menu1";
        const string KeyName2 = "Simple Context Menu2";

        // context menu text
        const string MenuText = "Copy to Grayscale";
        const string MenuText1 = "Resize all images";
        const string MenuText2 = "Share Media";

        public Form1()
        {
            InitializeComponent();

            listView1.View = View.List;

        }

        private void Args(string[] args)
        {
            // process register or unregister commands
            if (!ProcessCommand(args))
            {
                string action = args[0];
                string fileName = args[1];

                if (action == "Copy")
                {
                    // invoked from shell, process the selected file
                    CopyGrayscaleImage(fileName);
                }
                else if (action == "Resize")
                {
                    string FilePath = Path.Combine(
                    Path.GetDirectoryName(fileName),
                    string.Format("{0} (resized){1}",
                    Path.GetFileNameWithoutExtension(fileName),
                    Path.GetExtension(fileName)));
                    var directory = System.IO.Path.GetDirectoryName(fileName);
                    var files = System.IO.Directory.EnumerateFiles(directory, "*.*")
                        .Where(s => s.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase)
                                || s.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase)
                                || s.EndsWith(".tiff ", StringComparison.OrdinalIgnoreCase));
                    int count = 0;
                    foreach (string filename in files)
                    {
                        count++;
                        ImageResizer resizer = new ImageResizer(1024000, filename
                            , directory + "\\" + System.IO.Path.GetFileNameWithoutExtension(filename)
                            + "resized" + count + ".jpg");
                        resizer.ScaleImage();
                    }
                }
            }
        }

        /// <summary>
        /// Process command line actions (register or unregister).
        /// </summary>
        /// <param name="args">Command line arguments.</param>
        /// <returns>True if processed an action in the command line.</returns>
        private bool ProcessCommand(string[] args)
        {
            // register
            if (args.Length == 0 || string.Compare(args[0], "-register", true) == 0)
            {
                // full path to self, %L is placeholder for selected file
                string menuCommand = string.Format("\"{0}\" Copy \"%L\"", Application.ExecutablePath);

                // register the context menu
                FileShellExtension.Register(FileType,
                    KeyName, MenuText,
                    menuCommand);

                string menuCommand1 = string.Format("\"{0}\" Resize \"%L\"", Application.ExecutablePath);

                FileShellExtension.Register(FileType,
                    KeyName1, MenuText1,
                    menuCommand1);

                string menuCommand2 = string.Format("\"{0}\" Share \"%L\"", Application.ExecutablePath);

                FileShellExtension.Register(FileType,
                    KeyName2, MenuText2,
                    menuCommand2);

                using (Microsoft.Win32.RegistryKey key =
                    Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(@"HKEY_CLASSES_ROOT\jpegfile\shell\Simple Context Menu2"))
                // HKEY_CLASSES_ROOT\jpegfile\shell\Simple Context Menu2
                {
                    key.SetValue(null, "Tapuz");
                }

                MessageBox.Show(string.Format(
                    "The {0} shell extension was registered.",
                    KeyName), KeyName);

                return true;
            }

            // unregister       
            if (string.Compare(args[0], "-unregister", true) == 0)
            {
                // unregister the context menu
                FileShellExtension.Unregister(FileType, KeyName);

                MessageBox.Show(string.Format(
                    "The {0} shell extension was unregistered.",
                    KeyName), KeyName);

                return true;
            }

            // command line did not contain an action
            return false;
        }

        /// <summary>
        /// Make a grayscale copy of the image.
        /// </summary>
        /// <param name="filePath">Full path to the image to copy.</param>
        private void CopyGrayscaleImage(string filePath)
        {
            try
            {
                // full path to the grayscale copy
                string grayFilePath = Path.Combine(
                    Path.GetDirectoryName(filePath),
                    string.Format("{0} (grayscale){1}",
                    Path.GetFileNameWithoutExtension(filePath),
                    Path.GetExtension(filePath)));

                // using calls Dispose on the objects, important 
                // so the file is not locked when the app terminates
                using (Image image = new Bitmap(filePath))
                using (Bitmap grayImage = new Bitmap(image.Width, image.Height))
                using (Graphics g = Graphics.FromImage(grayImage))
                {
                    // setup grayscale matrix
                    ImageAttributes attr = new ImageAttributes();
                    attr.SetColorMatrix(new ColorMatrix(new float[][]{   
                        new float[]{0.3086F,0.3086F,0.3086F,0,0},
                        new float[]{0.6094F,0.6094F,0.6094F,0,0},
                        new float[]{0.082F,0.082F,0.082F,0,0},
                        new float[]{0,0,0,1,0,0},
                        new float[]{0,0,0,0,1,0},
                        new float[]{0,0,0,0,0,1}}));

                    // create the grayscale image
                    g.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height),
                        0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attr);

                    // save to the file system
                    grayImage.Save(grayFilePath, ImageFormat.Jpeg);

                    // success
                    MessageBox.Show(string.Format("Copied grayscale image {0}", grayFilePath), KeyName);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("An error occurred: {0}", ex.Message), KeyName);
                return;
            }
        }

        private Bitmap ResizeImages(String filename, int maxWidth, int maxHeight)
        {
            using (Image originalImage = Image.FromFile(filename))
            {
                //Caluate new Size
                int newWidth = originalImage.Width;
                int newHeight = originalImage.Height;
                double aspectRatio = (double)originalImage.Width / (double)originalImage.Height;
                if (aspectRatio <= 1 && originalImage.Width > maxWidth)
                {
                    newWidth = maxWidth;
                    newHeight = (int)Math.Round(newWidth / aspectRatio);
                }
                else if (aspectRatio > 1 && originalImage.Height > maxHeight)
                {
                    newHeight = maxHeight;
                    newWidth = (int)Math.Round(newHeight * aspectRatio);
                }
                if (newWidth >= 0 && newHeight >= 0)
                {
                    Bitmap newImage = new Bitmap(newWidth, newHeight);
                    using (Graphics g = Graphics.FromImage(newImage))
                    {
                        //--Quality Settings Adjust to fit your application
                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        g.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height);
                        return newImage;
                    }
                }
                return null;
            }
        }

        private void CopyFilesToClipBoard()
        {
            // Copy some files to the clipboard.
            List<string> file_list = new List<string>();
            foreach (string file_name in Directory.GetFiles(Application.StartupPath))
                file_list.Add(file_name);
            Clipboard.Clear();
            Clipboard.SetData(DataFormats.FileDrop, file_list.ToArray());
            // Paste the file list back out of the clipboard.
            string[] file_names = (string[])
            Clipboard.GetData(DataFormats.FileDrop);
            // Display the pasted file names.
            foreach (string fname in file_names)
                listView1.Items.Add(fname);
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

FileShellExtension类

using System;
using System.Diagnostics;
using Microsoft.Win32;

namespace ShellContextMenu
{
    /// <summary>
    /// Register and unregister simple shell context menus.
    /// </summary>
    static class FileShellExtension
    {
        /// <summary>
        /// Register a simple shell context menu.
        /// </summary>
        /// <param name="fileType">The file type to register.</param>
        /// <param name="shellKeyName">Name that appears in the registry.</param>
        /// <param name="menuText">Text that appears in the context menu.</param>
        /// <param name="menuCommand">Command line that is executed.</param>
        public static void Register(
            string fileType, string shellKeyName, 
            string menuText, string menuCommand)
        {
            Debug.Assert(!string.IsNullOrEmpty(fileType) &&
                !string.IsNullOrEmpty(shellKeyName) &&
                !string.IsNullOrEmpty(menuText) && 
                !string.IsNullOrEmpty(menuCommand));

            // create full path to registry location
            string regPath = string.Format(@"{0}\shell\{1}", fileType, shellKeyName);

            // add context menu to the registry
            using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(regPath))
            {
                key.SetValue(null, menuText);
            }

            // add command that is invoked to the registry
            using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(
                string.Format(@"{0}\command", regPath)))
            {               
                key.SetValue(null, menuCommand);
            }
        }

        /// <summary>
        /// Unregister a simple shell context menu.
        /// </summary>
        /// <param name="fileType">The file type to unregister.</param>
        /// <param name="shellKeyName">Name that was registered in the registry.</param>
        public static void Unregister(string fileType, string shellKeyName)
        {
            Debug.Assert(!string.IsNullOrEmpty(fileType) &&
                !string.IsNullOrEmpty(shellKeyName));

            // full path to the registry location           
            string regPath = string.Format(@"{0}\shell\{1}", fileType, shellKeyName);

            // remove context menu from the registry
            Registry.ClassesRoot.DeleteSubKeyTree(regPath);
        }
    }

}

1 个答案:

答案 0 :(得分:0)

这是一个非常垃圾的问题,在实际应用中,您的最小代码问题是如何访问命令行参数。

尝试

string[] args = Environment.GetCommandLineArgs();