简体   繁体   English

从上下文菜单返回一个字符串到 Windows (C#)

[英]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例如,我将命名为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.然后我将此程序添加为 Windows 注册表中的上下文菜单选项。

Except that doesn't work.除了那不起作用。 Apparently, I cannot return a string from the actual program.显然,我无法从实际程序中返回string

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?那么有没有办法将string从程序中取出并放入我的光标当时试图输入的任何内容中?

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.我建议您在 Windows 文件资源管理器中工作并添加一个Send To选项,该选项执行此操作并将当前选定的文件名传递到剪贴板。

The following takes the selected filename and adds a custom date after the name, but before the extension, such as TheFile.20211123.txt :以下采用选定的文件名并在名称之后但在扩展名之前添加自定义日期,例如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.构建程序并创建一个文件资源管理器快捷方式到构建的 exe。 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.然后在文件资源管理器中右键单击,选择Send To并选择您提供的快捷方式名称。

  • Then paste the new name where ever you need it, for it resides in your clipboard.然后将新名称粘贴到您需要的任何位置,因为它位于您的剪贴板中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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