简体   繁体   中英

Return a string to Windows from context menu (C#)

A common thing I do is name files by the current date/time. For instance, I'll name something 12-31-2016-08-46-01.jpg

This is great. It works well. But typing it every time is annoying, so I thought it useful to just write a small program that returns the output as a string. That was easy enough.

public class Program {
   public static string Main() {
      var strFilename = new DateTimeFilename();
      return strFilename.Current();
   }
public class DateTimeFilename {

   public string Current () {
      return // ... logic ... //
   }
}

And then I add this program as a context menu option in the Windows registry.

Except that doesn't work. Apparently, I cannot return a string from the actual program.

So is there a way to get the string out of the program and into whatever my cursor is trying to type into at the time?

I would recommend that you work within Windows File Explorer and add a Send To option which does this operation and passes the current selected file name to the clipboard.

The following takes the selected filename and adds a custom date after the name, but before the extension, such as TheFile.20211123.txt :

static void Main(string[] args)
{
    var name = $"{Path.GetFileNameWithoutExtension(args[0])}.{DateTime.Now.ToString("yyyyMMdd")}{Path.GetExtension(args[0])}";
    // MessageBox.Show(name);
    Clipboard.SetText(name);
}
  • Build the program and the create a file explorer short cut to the exe built. Then place the shortcut to this folder:

C:\\Users\\{username}\\AppData\\Roaming\\Microsoft\\Windows\\SendTo

  • Then in File Explorer right click, select Send To and select the shortcut name you gave it.

  • Then paste the new name where ever you need it, for it resides in your clipboard.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM