PowerShell + C# 实现桌面文字提醒,类似于“激活Windows”的功能

在网上本来想找个python实现类似于“激活Windows”的提示,如下图

kozkFyBU4cXm8XEyEEmGKA964db5a0784af214e54fee322e23f6f4

 找了一圈没有找到合适的,就又找deepseek找方案,deepseek也给了几个方案,最让我满意的还是 PowerShell + C# 实现的方案。

具体看以下给出的代码:

版本1

实现基本功能

$source = @"
using System;
using System.Drawing;
using System.Windows.Forms;

public class Watermark : Form
{
    private NotifyIcon trayIcon;
    private ContextMenuStrip trayMenu;
    private ToolStripMenuItem editModeItem;
    private ToolStripMenuItem toggleItem;
    private bool isExiting = false;
    private bool isEditMode = false;
    
    // 水印文字标签
    private Label watermarkLabel;
    
    // 编辑面板控件
    private Panel editPanel;
    private Label lblPosition;
    private TextBox txtX, txtY;
    private Label lblSize;
    private TextBox txtWidth, txtHeight;
    private Label lblText;
    private TextBox txtWatermarkText;
    private Button btnApply, btnSave, btnCancel;
    
    // 调整大小手柄
    private Panel resizeHandle;
    private Point dragStartPoint;
    private Size dragStartSize;
    private bool isResizing = false;
    
    // 保存编辑前的状态
    private Point savedLocation;
    private Size savedSize;
    private string savedText;

    [STAThread]
    static void Main()
    {
        bool createdNew;
        using (System.Threading.Mutex mutex = new System.Threading.Mutex(true, "DesktopWatermarkMutex", out createdNew))
        {
            if (!createdNew)
            {
                MessageBox.Show("桌面水印已经在运行中!\n请检查系统托盘图标。", "提示", 
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Watermark());
        }
    }

    public Watermark()
    {
        InitializeWatermark();
        CreateTrayIcon();
    }

    private void InitializeWatermark()
    {
        // ============ 窗口基础设置 ============
        this.FormBorderStyle = FormBorderStyle.None;
        this.ShowInTaskbar = false;
        this.TopMost = true;
        this.StartPosition = FormStartPosition.Manual;
        
        var screen = Screen.PrimaryScreen.WorkingArea;
        this.Size = new Size(600, 200);
        this.Location = new Point(screen.Right - 610, screen.Bottom - 210);
        this.MinimumSize = new Size(200, 60);
        
        this.BackColor = Color.Black;
        this.TransparencyKey = Color.Black;
        this.Opacity = 0.9;
        
        // ============ 水印文字标签 ============
        watermarkLabel = new Label
        {
            Text = "Windows 10 专业版\r\nBuild 19045\r\n联系IT部门激活",
            ForeColor = Color.White,
            Font = new Font("Microsoft YaHei", 29, FontStyle.Regular),
            TextAlign = ContentAlignment.BottomRight,
            Dock = DockStyle.Fill,
            Padding = new Padding(0, 0, 10, 5)
        };
        this.Controls.Add(watermarkLabel);
        
        // ============ 编辑面板(初始隐藏) ============
        CreateEditPanel();
        
        // ============ 调整大小手柄(初始隐藏) ============
        resizeHandle = new Panel
        {
            Size = new Size(16, 16),
            BackColor = Color.White,
            Cursor = Cursors.SizeNWSE,
            Visible = false
        };
        resizeHandle.MouseDown += ResizeHandle_MouseDown;
        resizeHandle.MouseMove += ResizeHandle_MouseMove;
        resizeHandle.MouseUp += ResizeHandle_MouseUp;
        this.Controls.Add(resizeHandle);
        
        // ============ 事件处理 ============
        this.MouseDown += Window_MouseDown;
        this.FormClosing += Window_FormClosing;
        this.Resize += Window_Resize;
        this.Move += Window_Move;
    }

    private void CreateEditPanel()
    {
        editPanel = new Panel
        {
            Size = new Size(350, 200),
            BackColor = Color.FromArgb(240, 240, 240),
            Visible = false,
            BorderStyle = BorderStyle.FixedSingle
        };

        int y = 10;
        int leftMargin = 10;
        int labelWidth = 50;
        int inputWidth = 70;

        // 位置设置
        lblPosition = new Label
        {
            Text = "位置:",
            Location = new Point(leftMargin, y),
            Size = new Size(labelWidth, 25)
        };
        editPanel.Controls.Add(lblPosition);

        txtX = new TextBox
        {
            Location = new Point(leftMargin + labelWidth, y),
            Size = new Size(inputWidth, 25)
        };
        editPanel.Controls.Add(txtX);

        Label lblX = new Label
        {
            Text = "X",
            Location = new Point(leftMargin + labelWidth + inputWidth + 5, y),
            Size = new Size(20, 25)
        };
        editPanel.Controls.Add(lblX);

        txtY = new TextBox
        {
            Location = new Point(leftMargin + labelWidth + inputWidth + 30, y),
            Size = new Size(inputWidth, 25)
        };
        editPanel.Controls.Add(txtY);

        Label lblY = new Label
        {
            Text = "Y",
            Location = new Point(leftMargin + labelWidth + inputWidth * 2 + 35, y),
            Size = new Size(20, 25)
        };
        editPanel.Controls.Add(lblY);

        y += 30;

        // 大小设置
        lblSize = new Label
        {
            Text = "大小:",
            Location = new Point(leftMargin, y),
            Size = new Size(labelWidth, 25)
        };
        editPanel.Controls.Add(lblSize);

        txtWidth = new TextBox
        {
            Location = new Point(leftMargin + labelWidth, y),
            Size = new Size(inputWidth, 25)
        };
        editPanel.Controls.Add(txtWidth);

        Label lblW = new Label
        {
            Text = "W",
            Location = new Point(leftMargin + labelWidth + inputWidth + 5, y),
            Size = new Size(20, 25)
        };
        editPanel.Controls.Add(lblW);

        txtHeight = new TextBox
        {
            Location = new Point(leftMargin + labelWidth + inputWidth + 30, y),
            Size = new Size(inputWidth, 25)
        };
        editPanel.Controls.Add(txtHeight);

        Label lblH = new Label
        {
            Text = "H",
            Location = new Point(leftMargin + labelWidth + inputWidth * 2 + 35, y),
            Size = new Size(20, 25)
        };
        editPanel.Controls.Add(lblH);

        y += 35;

        // 文字内容设置
        lblText = new Label
        {
            Text = "文字:",
            Location = new Point(leftMargin, y),
            Size = new Size(labelWidth, 25)
        };
        editPanel.Controls.Add(lblText);

        txtWatermarkText = new TextBox
        {
            Location = new Point(leftMargin + labelWidth, y),
            Size = new Size(300, 60),
            Multiline = true,
            ScrollBars = ScrollBars.Vertical
        };
        editPanel.Controls.Add(txtWatermarkText);

        y += 70;

        // 按钮
        btnApply = new Button
        {
            Text = "应用",
            Location = new Point(leftMargin + labelWidth, y),
            Size = new Size(70, 30)
        };
        btnApply.Click += BtnApply_Click;
        editPanel.Controls.Add(btnApply);

        btnSave = new Button
        {
            Text = "保存",
            Location = new Point(leftMargin + labelWidth + 80, y),
            Size = new Size(70, 30)
        };
        btnSave.Click += BtnSave_Click;
        editPanel.Controls.Add(btnSave);

        btnCancel = new Button
        {
            Text = "取消",
            Location = new Point(leftMargin + labelWidth + 160, y),
            Size = new Size(70, 30)
        };
        btnCancel.Click += BtnCancel_Click;
        editPanel.Controls.Add(btnCancel);

        this.Controls.Add(editPanel);
    }

    // ============ 窗口拖动 ============
    private void Window_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            this.Capture = false;
            Message msg = Message.Create(this.Handle, 0xA1, new IntPtr(2), IntPtr.Zero);
            this.DefWndProc(ref msg);
        }
    }

    // ============ 窗口大小调整事件 ============
    private void Window_Resize(object sender, EventArgs e)
    {
        if (isEditMode)
        {
            resizeHandle.Location = new Point(this.Width - resizeHandle.Width, this.Height - resizeHandle.Height);
            UpdateEditPanelValues();
            UpdateEditPanelPosition();
        }
    }

    private void Window_Move(object sender, EventArgs e)
    {
        if (isEditMode)
        {
            UpdateEditPanelValues();
            UpdateEditPanelPosition();
        }
    }

    // ============ 调整大小手柄事件 ============
    private void ResizeHandle_MouseDown(object sender, MouseEventArgs e)
    {
        isResizing = true;
        dragStartPoint = Cursor.Position;
        dragStartSize = this.Size;
    }

    private void ResizeHandle_MouseMove(object sender, MouseEventArgs e)
    {
        if (isResizing)
        {
            Point currentPoint = Cursor.Position;
            int newWidth = dragStartSize.Width + (currentPoint.X - dragStartPoint.X);
            int newHeight = dragStartSize.Height + (currentPoint.Y - dragStartPoint.Y);
            
            newWidth = Math.Max(this.MinimumSize.Width, newWidth);
            newHeight = Math.Max(this.MinimumSize.Height, newHeight);
            
            this.Size = new Size(newWidth, newHeight);
        }
    }

    private void ResizeHandle_MouseUp(object sender, MouseEventArgs e)
    {
        isResizing = false;
    }

    // ============ 编辑面板按钮事件 ============
    private void BtnApply_Click(object sender, EventArgs e)
    {
        try
        {
            int x = int.Parse(txtX.Text);
            int y = int.Parse(txtY.Text);
            int width = int.Parse(txtWidth.Text);
            int height = int.Parse(txtHeight.Text);
            
            width = Math.Max(this.MinimumSize.Width, width);
            height = Math.Max(this.MinimumSize.Height, height);
            
            this.Location = new Point(x, y);
            this.Size = new Size(width, height);
            watermarkLabel.Text = txtWatermarkText.Text;
        }
        catch
        {
            MessageBox.Show("请输入有效的数字!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void BtnSave_Click(object sender, EventArgs e)
    {
        BtnApply_Click(sender, e);
        ExitEditMode();
    }

    private void BtnCancel_Click(object sender, EventArgs e)
    {
        // 恢复原始状态
        this.Location = savedLocation;
        this.Size = savedSize;
        watermarkLabel.Text = savedText;
        ExitEditMode();
    }

    // ============ 编辑模式切换 ============
    private void EnterEditMode()
    {
        if (isEditMode) return;
        
        // 保存当前状态
        savedLocation = this.Location;
        savedSize = this.Size;
        savedText = watermarkLabel.Text;
        
        // 切换到编辑模式
        isEditMode = true;
        this.FormBorderStyle = FormBorderStyle.Sizable;
        this.BackColor = Color.FromArgb(50, 50, 50);
        this.TransparencyKey = Color.Empty;  // 取消透明
        this.Opacity = 0.95;
        
        // 显示编辑控件
        resizeHandle.Visible = true;
        resizeHandle.Location = new Point(this.Width - resizeHandle.Width, this.Height - resizeHandle.Height);
        resizeHandle.BringToFront();
        
        editPanel.Visible = true;
        UpdateEditPanelValues();
        UpdateEditPanelPosition();
        editPanel.BringToFront();
        
        // 更新菜单
        editModeItem.Text = "退出编辑模式";
    }

    private void ExitEditMode()
    {
        if (!isEditMode) return;
        
        // 恢复普通模式
        isEditMode = false;
        this.FormBorderStyle = FormBorderStyle.None;
        this.BackColor = Color.Black;
        this.TransparencyKey = Color.Black;
        this.Opacity = 0.85;
        
        // 隐藏编辑控件
        resizeHandle.Visible = false;
        editPanel.Visible = false;
        
        // 更新菜单
        editModeItem.Text = "编辑模式";
    }

    private void UpdateEditPanelValues()
    {
        txtX.Text = this.Left.ToString();
        txtY.Text = this.Top.ToString();
        txtWidth.Text = this.Width.ToString();
        txtHeight.Text = this.Height.ToString();
        txtWatermarkText.Text = watermarkLabel.Text;
    }

    private void UpdateEditPanelPosition()
    {
        // 将编辑面板放在窗口下方
        int panelX = Math.Max(0, this.Left + (this.Width - editPanel.Width) / 2);
        int panelY = this.Bottom + 5;
        
        // 确保不超出屏幕
        var screen = Screen.PrimaryScreen.WorkingArea;
        if (panelX + editPanel.Width > screen.Right) panelX = screen.Right - editPanel.Width - 10;
        if (panelY + editPanel.Height > screen.Bottom) panelY = this.Top - editPanel.Height - 5;
        
        editPanel.Location = new Point(panelX, panelY);
    }

    // ============ 窗口关闭事件 ============
    private void Window_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (!isExiting)
        {
            e.Cancel = true;
            this.Hide();
            trayIcon.ShowBalloonTip(3000, "桌面水印", "水印已最小化到系统托盘\n右键图标可退出", ToolTipIcon.Info);
        }
    }

    // ============ 系统托盘图标 ============
    private void CreateTrayIcon()
    {
        trayMenu = new ContextMenuStrip();

        // 显示/隐藏菜单项
        toggleItem = new ToolStripMenuItem("隐藏水印");
        toggleItem.Click += (sender, e) => {
            if (this.Visible)
            {
                this.Hide();
                toggleItem.Text = "显示水印";
            }
            else
            {
                this.Show();
                toggleItem.Text = "隐藏水印";
            }
        };
        trayMenu.Items.Add(toggleItem);

        // 编辑模式菜单项
        editModeItem = new ToolStripMenuItem("编辑模式");
        editModeItem.Click += (sender, e) => {
            if (isEditMode)
            {
                ExitEditMode();
            }
            else
            {
                EnterEditMode();
            }
        };
        trayMenu.Items.Add(editModeItem);
        trayMenu.Items.Add(new ToolStripSeparator());

        // 关于菜单项
        ToolStripMenuItem aboutItem = new ToolStripMenuItem("关于");
        aboutItem.Click += (sender, e) => {
            MessageBox.Show("桌面水印工具 v1.0\n\n功能:\n? 编辑模式:调整位置、大小、文字\n? 拖拽调整窗口大小\n? 右键托盘图标操作", 
                "关于", MessageBoxButtons.OK, MessageBoxIcon.Information);
        };
        trayMenu.Items.Add(aboutItem);
        trayMenu.Items.Add(new ToolStripSeparator());

        // 退出菜单项
        ToolStripMenuItem exitItem = new ToolStripMenuItem("退出");
        exitItem.Click += (sender, e) => {
            ExitApplication();
        };
        trayMenu.Items.Add(exitItem);

        // 创建托盘图标
        trayIcon = new NotifyIcon
        {
            Text = "桌面水印 - 右键菜单",
            Icon = CreateTrayIconImage(),
            ContextMenuStrip = trayMenu,
            Visible = true
        };

        trayIcon.MouseDoubleClick += (sender, e) => {
            if (this.Visible)
            {
                this.Hide();
                toggleItem.Text = "显示水印";
            }
            else
            {
                this.Show();
                toggleItem.Text = "隐藏水印";
            }
        };
    }

    private Icon CreateTrayIconImage()
    {
        try
        {
            if (System.IO.File.Exists("watermark.ico"))
            {
                return new Icon("watermark.ico");
            }
        }
        catch { }

        Bitmap bitmap = new Bitmap(32, 32);
        using (Graphics g = Graphics.FromImage(bitmap))
        {
            g.Clear(Color.DarkBlue);
            using (Font font = new Font("Microsoft YaHei", 16, FontStyle.Bold))
            {
                g.DrawString("W", font, Brushes.White, 4, 2);
            }
        }
        return Icon.FromHandle(bitmap.GetHicon());
    }

    private void ExitApplication()
    {
        isExiting = true;
        
        if (trayIcon != null)
        {
            trayIcon.Visible = false;
            trayIcon.Dispose();
        }
        
        this.Close();
        Application.Exit();
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            trayIcon.Dispose();
            trayMenu.Dispose();
        }
        base.Dispose(disposing);
    }
}
"@

Add-Type -TypeDefinition $source -ReferencedAssemblies "System.Windows.Forms", "System.Drawing" -OutputAssembly "watermark.exe" -OutputType WindowsApplication

Write-Host "编译成功!watermark.exe 已生成" -ForegroundColor Green
Write-Host ""
Write-Host "功能说明:" -ForegroundColor Cyan
Write-Host "  【普通模式】" -ForegroundColor White
Write-Host "  - 双击托盘图标:显示/隐藏水印" -ForegroundColor Gray
Write-Host "  - 左键拖动水印:移动位置" -ForegroundColor Gray
Write-Host "  - 关闭窗口:最小化到托盘" -ForegroundColor Gray
Write-Host ""
Write-Host "  【编辑模式】右键托盘 → 编辑模式" -ForegroundColor Yellow
Write-Host "  - 窗口显示边框,可拖拽调整大小" -ForegroundColor Gray
Write-Host "  - 右下角白色方块:拖拽调整大小" -ForegroundColor Gray
Write-Host "  - 编辑面板:修改位置/大小/文字" -ForegroundColor Gray
Write-Host "  - 应用:预览修改效果" -ForegroundColor Gray
Write-Host "  - 保存:保存并退出编辑模式" -ForegroundColor Gray
Write-Host "  - 取消:恢复原始状态" -ForegroundColor Gray
Write-Host ""
Write-Host "  - 完全退出:右键托盘 → 退出" -ForegroundColor Red
View Code

 

 

版本2

命令还运行时,可以动态设置运行参数

$source = @"
using System;
using System.Drawing;
using System.Windows.Forms;

public class Watermark : Form
{
    private NotifyIcon trayIcon;
    private ContextMenuStrip trayMenu;
    private ToolStripMenuItem editModeItem;
    private ToolStripMenuItem toggleItem;
    private bool isExiting = false;
    private bool isEditMode = false;
    
    // 默认参数
    private static string defaultText = "Windows 10 专业版\r\nBuild 19045\r\n联系IT部门激活";
    private static int defaultX = -1;
    private static int defaultY = -1;
    private static int defaultWidth = 600;
    private static int defaultHeight = 200;
    private static float defaultOpacity = 0.9F;
    private static int defaultFontSize = 29;
    private static string defaultFontColor = "White";
    
    // 水印文字标签
    private Label watermarkLabel;
    
    // 编辑面板控件
    private Panel editPanel;
    private Label lblPosition;
    private TextBox txtX, txtY;
    private Label lblSize;
    private TextBox txtWidth, txtHeight;
    private Label lblText;
    private TextBox txtWatermarkText;
    private Button btnApply, btnSave, btnCancel;
    
    // 调整大小手柄
    private Panel resizeHandle;
    private Point dragStartPoint;
    private Size dragStartSize;
    private bool isResizing = false;
    
    // 保存编辑前的状态
    private Point savedLocation;
    private Size savedSize;
    private string savedText;

    [STAThread]
    static void Main(string[] args)
    {
        // 解析命令行参数
        ParseArguments(args);
        
        bool createdNew;
        using (System.Threading.Mutex mutex = new System.Threading.Mutex(true, "DesktopWatermarkMutex", out createdNew))
        {
            if (!createdNew)
            {
                // 如果已有实例运行,尝试通过WM_COPYDATA传递新文本
                IntPtr hWnd = FindWindow(null, "DesktopWatermark");
                if (hWnd != IntPtr.Zero && args.Length > 0)
                {
                    // 发送更新文本的消息
                    SendMessage(hWnd, 0x004A, IntPtr.Zero, string.Join(" ", args));
                }
                else
                {
                    MessageBox.Show("桌面水印已经在运行中!\n请检查系统托盘图标。", "提示", 
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                return;
            }
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Watermark());
        }
    }

    private static void ParseArguments(string[] args)
    {
        for (int i = 0; i < args.Length; i++)
        {
            string arg = args[i].ToLower();
            
            switch (arg)
            {
                case "-text":
                case "-t":
                    if (i + 1 < args.Length)
                    {
                        defaultText = args[++i].Replace("\\n", "\r\n").Replace("\\r\\n", "\r\n");
                    }
                    break;
                case "-x":
                    if (i + 1 < args.Length) int.TryParse(args[++i], out defaultX);
                    break;
                case "-y":
                    if (i + 1 < args.Length) int.TryParse(args[++i], out defaultY);
                    break;
                case "-width":
                case "-w":
                    if (i + 1 < args.Length) int.TryParse(args[++i], out defaultWidth);
                    break;
                case "-height":
                case "-h":
                    if (i + 1 < args.Length) int.TryParse(args[++i], out defaultHeight);
                    break;
                case "-opacity":
                case "-o":
                    if (i + 1 < args.Length) float.TryParse(args[++i], out defaultOpacity);
                    break;
                case "-fontsize":
                case "-fs":
                    if (i + 1 < args.Length) int.TryParse(args[++i], out defaultFontSize);
                    break;
                case "-fontcolor":
                case "-fc":
                    if (i + 1 < args.Length) defaultFontColor = args[++i];
                    break;
                case "-help":
                case "--help":
                case "-?":
                    ShowHelp();
                    Environment.Exit(0);
                    break;
                default:
                    // 如果没有参数标识,将整个参数作为文本
                    if (!arg.StartsWith("-") && i == 0)
                    {
                        defaultText = string.Join(" ", args).Replace("\\n", "\r\n").Replace("\\r\\n", "\r\n");
                        break;
                    }
                    break;
            }
        }
    }

    private static void ShowHelp()
    {
        string help = @"
桌面水印工具 v1.0 - 命令行参数说明
====================================

用法: watermark.exe [选项]

选项:
  -text, -t <文本>     设置水印文字(用 \n 表示换行)
  -x <数值>            设置窗口X坐标
  -y <数值>            设置窗口Y坐标
  -width, -w <数值>    设置窗口宽度(默认600)
  -height, -h <数值>   设置窗口高度(默认200)
  -opacity, -o <数值>  设置透明度 0.1-1.0(默认0.9-fontsize, -fs <数值> 设置字体大小(默认29)
  -fontcolor, -fc <颜色> 设置字体颜色(默认White)
  -help, --help        显示此帮助信息

示例:
  watermark.exe -text ""服务器监控中\n请勿关闭""
  watermark.exe -t ""温馨提示\n注意安全"" -x 100 -y 100
  watermark.exe -text ""系统维护中"" -opacity 0.7 -fontsize 20 -fontcolor Yellow
  watermark.exe ""直接写文字也可以""
";
        MessageBox.Show(help, "帮助", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }

    // Windows API 声明
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam);

    public Watermark()
    {
        this.Text = "DesktopWatermark";  // 用于FindWindow查找
        InitializeWatermark();
        CreateTrayIcon();
        SetupMessageFilter();
    }

    private void SetupMessageFilter()
    {
        // 允许接收来自其他进程的消息
        Application.AddMessageFilter(new CopyDataMessageFilter(this));
    }

    // 消息过滤器,用于接收其他实例发送的文字更新
    private class CopyDataMessageFilter : IMessageFilter
    {
        private Watermark form;
        
        public CopyDataMessageFilter(Watermark form)
        {
            this.form = form;
        }
        
        public bool PreFilterMessage(ref Message m)
        {
            if (m.Msg == 0x004A)  // WM_COPYDATA
            {
                form.UpdateWatermarkText(m.LParam.ToString());
                return true;
            }
            return false;
        }
    }

    public void UpdateWatermarkText(string newText)
    {
        if (this.InvokeRequired)
        {
            this.Invoke(new Action<string>(UpdateWatermarkText), newText);
            return;
        }
        
        if (!string.IsNullOrEmpty(newText))
        {
            newText = newText.Replace("\\n", "\r\n").Replace("\\r\\n", "\r\n");
            watermarkLabel.Text = newText;
            if (txtWatermarkText != null)
            {
                txtWatermarkText.Text = newText;
            }
        }
    }

    private void InitializeWatermark()
    {
        // ============ 窗口基础设置 ============
        this.FormBorderStyle = FormBorderStyle.None;
        this.ShowInTaskbar = false;
        this.TopMost = true;
        this.StartPosition = FormStartPosition.Manual;
        
        var screen = Screen.PrimaryScreen.WorkingArea;
        this.Size = new Size(defaultWidth, defaultHeight);
        
        // 设置位置:如果指定了X/Y则使用,否则默认右下角
        int posX = (defaultX >= 0) ? defaultX : screen.Right - defaultWidth - 10;
        int posY = (defaultY >= 0) ? defaultY : screen.Bottom - defaultHeight - 10;
        this.Location = new Point(posX, posY);
        
        this.MinimumSize = new Size(200, 60);
        this.BackColor = Color.Black;
        this.TransparencyKey = Color.Black;
        this.Opacity = Math.Max(0.1, Math.Min(1.0, defaultOpacity));
        
        // ============ 解析字体颜色 ============
        Color fontColor;
        try
        {
            fontColor = Color.FromName(defaultFontColor);
            if (!fontColor.IsKnownColor && !fontColor.IsSystemColor)
            {
                fontColor = Color.White;  // 默认白色
            }
        }
        catch
        {
            fontColor = Color.White;
        }
        
        // ============ 水印文字标签 ============
        watermarkLabel = new Label
        {
            Text = defaultText,
            ForeColor = fontColor,
            Font = new Font("Microsoft YaHei", defaultFontSize, FontStyle.Regular),
            TextAlign = ContentAlignment.BottomRight,
            Dock = DockStyle.Fill,
            Padding = new Padding(0, 0, 10, 5)
        };
        this.Controls.Add(watermarkLabel);
        
        // ============ 编辑面板(初始隐藏) ============
        CreateEditPanel();
        
        // ============ 调整大小手柄(初始隐藏) ============
        resizeHandle = new Panel
        {
            Size = new Size(16, 16),
            BackColor = Color.White,
            Cursor = Cursors.SizeNWSE,
            Visible = false
        };
        resizeHandle.MouseDown += ResizeHandle_MouseDown;
        resizeHandle.MouseMove += ResizeHandle_MouseMove;
        resizeHandle.MouseUp += ResizeHandle_MouseUp;
        this.Controls.Add(resizeHandle);
        
        // ============ 事件处理 ============
        this.MouseDown += Window_MouseDown;
        this.FormClosing += Window_FormClosing;
        this.Resize += Window_Resize;
        this.Move += Window_Move;
    }

    private void CreateEditPanel()
    {
        editPanel = new Panel
        {
            Size = new Size(350, 200),
            BackColor = Color.FromArgb(240, 240, 240),
            Visible = false,
            BorderStyle = BorderStyle.FixedSingle
        };

        int y = 10;
        int leftMargin = 10;
        int labelWidth = 50;
        int inputWidth = 70;

        // 位置设置
        lblPosition = new Label
        {
            Text = "位置:",
            Location = new Point(leftMargin, y),
            Size = new Size(labelWidth, 25)
        };
        editPanel.Controls.Add(lblPosition);

        txtX = new TextBox
        {
            Location = new Point(leftMargin + labelWidth, y),
            Size = new Size(inputWidth, 25)
        };
        editPanel.Controls.Add(txtX);

        Label lblX = new Label
        {
            Text = "X",
            Location = new Point(leftMargin + labelWidth + inputWidth + 5, y),
            Size = new Size(20, 25)
        };
        editPanel.Controls.Add(lblX);

        txtY = new TextBox
        {
            Location = new Point(leftMargin + labelWidth + inputWidth + 30, y),
            Size = new Size(inputWidth, 25)
        };
        editPanel.Controls.Add(txtY);

        Label lblY = new Label
        {
            Text = "Y",
            Location = new Point(leftMargin + labelWidth + inputWidth * 2 + 35, y),
            Size = new Size(20, 25)
        };
        editPanel.Controls.Add(lblY);

        y += 30;

        // 大小设置
        lblSize = new Label
        {
            Text = "大小:",
            Location = new Point(leftMargin, y),
            Size = new Size(labelWidth, 25)
        };
        editPanel.Controls.Add(lblSize);

        txtWidth = new TextBox
        {
            Location = new Point(leftMargin + labelWidth, y),
            Size = new Size(inputWidth, 25)
        };
        editPanel.Controls.Add(txtWidth);

        Label lblW = new Label
        {
            Text = "W",
            Location = new Point(leftMargin + labelWidth + inputWidth + 5, y),
            Size = new Size(20, 25)
        };
        editPanel.Controls.Add(lblW);

        txtHeight = new TextBox
        {
            Location = new Point(leftMargin + labelWidth + inputWidth + 30, y),
            Size = new Size(inputWidth, 25)
        };
        editPanel.Controls.Add(txtHeight);

        Label lblH = new Label
        {
            Text = "H",
            Location = new Point(leftMargin + labelWidth + inputWidth * 2 + 35, y),
            Size = new Size(20, 25)
        };
        editPanel.Controls.Add(lblH);

        y += 35;

        // 文字内容设置
        lblText = new Label
        {
            Text = "文字:",
            Location = new Point(leftMargin, y),
            Size = new Size(labelWidth, 25)
        };
        editPanel.Controls.Add(lblText);

        txtWatermarkText = new TextBox
        {
            Location = new Point(leftMargin + labelWidth, y),
            Size = new Size(300, 60),
            Multiline = true,
            ScrollBars = ScrollBars.Vertical
        };
        editPanel.Controls.Add(txtWatermarkText);

        y += 70;

        // 按钮
        btnApply = new Button
        {
            Text = "应用",
            Location = new Point(leftMargin + labelWidth, y),
            Size = new Size(70, 30)
        };
        btnApply.Click += BtnApply_Click;
        editPanel.Controls.Add(btnApply);

        btnSave = new Button
        {
            Text = "保存",
            Location = new Point(leftMargin + labelWidth + 80, y),
            Size = new Size(70, 30)
        };
        btnSave.Click += BtnSave_Click;
        editPanel.Controls.Add(btnSave);

        btnCancel = new Button
        {
            Text = "取消",
            Location = new Point(leftMargin + labelWidth + 160, y),
            Size = new Size(70, 30)
        };
        btnCancel.Click += BtnCancel_Click;
        editPanel.Controls.Add(btnCancel);

        this.Controls.Add(editPanel);
    }

    // ============ 窗口拖动 ============
    private void Window_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            this.Capture = false;
            Message msg = Message.Create(this.Handle, 0xA1, new IntPtr(2), IntPtr.Zero);
            this.DefWndProc(ref msg);
        }
    }

    // ============ 窗口大小调整事件 ============
    private void Window_Resize(object sender, EventArgs e)
    {
        if (isEditMode)
        {
            resizeHandle.Location = new Point(this.Width - resizeHandle.Width, this.Height - resizeHandle.Height);
            UpdateEditPanelValues();
            UpdateEditPanelPosition();
        }
    }

    private void Window_Move(object sender, EventArgs e)
    {
        if (isEditMode)
        {
            UpdateEditPanelValues();
            UpdateEditPanelPosition();
        }
    }

    // ============ 调整大小手柄事件 ============
    private void ResizeHandle_MouseDown(object sender, MouseEventArgs e)
    {
        isResizing = true;
        dragStartPoint = Cursor.Position;
        dragStartSize = this.Size;
    }

    private void ResizeHandle_MouseMove(object sender, MouseEventArgs e)
    {
        if (isResizing)
        {
            Point currentPoint = Cursor.Position;
            int newWidth = dragStartSize.Width + (currentPoint.X - dragStartPoint.X);
            int newHeight = dragStartSize.Height + (currentPoint.Y - dragStartPoint.Y);
            
            newWidth = Math.Max(this.MinimumSize.Width, newWidth);
            newHeight = Math.Max(this.MinimumSize.Height, newHeight);
            
            this.Size = new Size(newWidth, newHeight);
        }
    }

    private void ResizeHandle_MouseUp(object sender, MouseEventArgs e)
    {
        isResizing = false;
    }

    // ============ 编辑面板按钮事件 ============
    private void BtnApply_Click(object sender, EventArgs e)
    {
        try
        {
            int x = int.Parse(txtX.Text);
            int y = int.Parse(txtY.Text);
            int width = int.Parse(txtWidth.Text);
            int height = int.Parse(txtHeight.Text);
            
            width = Math.Max(this.MinimumSize.Width, width);
            height = Math.Max(this.MinimumSize.Height, height);
            
            this.Location = new Point(x, y);
            this.Size = new Size(width, height);
            watermarkLabel.Text = txtWatermarkText.Text;
        }
        catch
        {
            MessageBox.Show("请输入有效的数字!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void BtnSave_Click(object sender, EventArgs e)
    {
        BtnApply_Click(sender, e);
        ExitEditMode();
    }

    private void BtnCancel_Click(object sender, EventArgs e)
    {
        this.Location = savedLocation;
        this.Size = savedSize;
        watermarkLabel.Text = savedText;
        ExitEditMode();
    }

    // ============ 编辑模式切换 ============
    private void EnterEditMode()
    {
        if (isEditMode) return;
        
        savedLocation = this.Location;
        savedSize = this.Size;
        savedText = watermarkLabel.Text;
        
        isEditMode = true;
        this.FormBorderStyle = FormBorderStyle.Sizable;
        this.BackColor = Color.FromArgb(50, 50, 50);
        this.TransparencyKey = Color.Empty;
        this.Opacity = 0.95;
        
        resizeHandle.Visible = true;
        resizeHandle.Location = new Point(this.Width - resizeHandle.Width, this.Height - resizeHandle.Height);
        resizeHandle.BringToFront();
        
        editPanel.Visible = true;
        UpdateEditPanelValues();
        UpdateEditPanelPosition();
        editPanel.BringToFront();
        
        editModeItem.Text = "退出编辑模式";
    }

    private void ExitEditMode()
    {
        if (!isEditMode) return;
        
        isEditMode = false;
        this.FormBorderStyle = FormBorderStyle.None;
        this.BackColor = Color.Black;
        this.TransparencyKey = Color.Black;
        this.Opacity = defaultOpacity;
        
        resizeHandle.Visible = false;
        editPanel.Visible = false;
        
        editModeItem.Text = "编辑模式";
    }

    private void UpdateEditPanelValues()
    {
        txtX.Text = this.Left.ToString();
        txtY.Text = this.Top.ToString();
        txtWidth.Text = this.Width.ToString();
        txtHeight.Text = this.Height.ToString();
        txtWatermarkText.Text = watermarkLabel.Text;
    }

    private void UpdateEditPanelPosition()
    {
        int panelX = Math.Max(0, this.Left + (this.Width - editPanel.Width) / 2);
        int panelY = this.Bottom + 5;
        
        var screen = Screen.PrimaryScreen.WorkingArea;
        if (panelX + editPanel.Width > screen.Right) panelX = screen.Right - editPanel.Width - 10;
        if (panelY + editPanel.Height > screen.Bottom) panelY = this.Top - editPanel.Height - 5;
        
        editPanel.Location = new Point(panelX, panelY);
    }

    // ============ 窗口关闭事件 ============
    private void Window_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (!isExiting)
        {
            e.Cancel = true;
            this.Hide();
            trayIcon.ShowBalloonTip(3000, "桌面水印", "水印已最小化到系统托盘\n右键图标可退出", ToolTipIcon.Info);
        }
    }

    // ============ 系统托盘图标 ============
    private void CreateTrayIcon()
    {
        trayMenu = new ContextMenuStrip();

        toggleItem = new ToolStripMenuItem("隐藏水印");
        toggleItem.Click += (sender, e) => {
            if (this.Visible)
            {
                this.Hide();
                toggleItem.Text = "显示水印";
            }
            else
            {
                this.Show();
                toggleItem.Text = "隐藏水印";
            }
        };
        trayMenu.Items.Add(toggleItem);

        editModeItem = new ToolStripMenuItem("编辑模式");
        editModeItem.Click += (sender, e) => {
            if (isEditMode)
            {
                ExitEditMode();
            }
            else
            {
                EnterEditMode();
            }
        };
        trayMenu.Items.Add(editModeItem);
        trayMenu.Items.Add(new ToolStripSeparator());

        ToolStripMenuItem aboutItem = new ToolStripMenuItem("关于");
        aboutItem.Click += (sender, e) => {
            MessageBox.Show("桌面水印工具 v1.0\n\n功能:\n? 编辑模式:调整位置、大小、文字\n? 命令行参数自定义\n? 拖拽调整窗口大小\n? 右键托盘图标操作\n\n命令行帮助: watermark.exe -help", 
                "关于", MessageBoxButtons.OK, MessageBoxIcon.Information);
        };
        trayMenu.Items.Add(aboutItem);
        trayMenu.Items.Add(new ToolStripSeparator());

        ToolStripMenuItem exitItem = new ToolStripMenuItem("退出");
        exitItem.Click += (sender, e) => {
            ExitApplication();
        };
        trayMenu.Items.Add(exitItem);

        trayIcon = new NotifyIcon
        {
            Text = "桌面水印 - 右键菜单",
            Icon = CreateTrayIconImage(),
            ContextMenuStrip = trayMenu,
            Visible = true
        };

        trayIcon.MouseDoubleClick += (sender, e) => {
            if (this.Visible)
            {
                this.Hide();
                toggleItem.Text = "显示水印";
            }
            else
            {
                this.Show();
                toggleItem.Text = "隐藏水印";
            }
        };
    }

    private Icon CreateTrayIconImage()
    {
        try
        {
            if (System.IO.File.Exists("watermark.ico"))
            {
                return new Icon("watermark.ico");
            }
        }
        catch { }

        Bitmap bitmap = new Bitmap(32, 32);
        using (Graphics g = Graphics.FromImage(bitmap))
        {
            //设置图标背景色[DarkBlue,White][]
            //g.Clear(Color.DarkBlue);
            using (Font font = new Font("Microsoft YaHei", 16, FontStyle.Bold))
            {
                g.DrawString("W", font, Brushes.DarkBlue, 4, 2);
            }
        }
        return Icon.FromHandle(bitmap.GetHicon());
    }

    private void ExitApplication()
    {
        isExiting = true;
        
        if (trayIcon != null)
        {
            trayIcon.Visible = false;
            trayIcon.Dispose();
        }
        
        this.Close();
        Application.Exit();
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            trayIcon.Dispose();
            trayMenu.Dispose();
        }
        base.Dispose(disposing);
    }
}
"@

Add-Type -TypeDefinition $source -ReferencedAssemblies "System.Windows.Forms", "System.Drawing" -OutputAssembly "watermark.exe" -OutputType WindowsApplication

Write-Host "编译成功!watermark.exe 已生成" -ForegroundColor Green
Write-Host ""
Write-Host "命令行使用示例:" -ForegroundColor Cyan
Write-Host "  watermark.exe -text ""服务器监控中\n请勿关闭""" -ForegroundColor Yellow
Write-Host "  watermark.exe -t ""注意安全"" -x 100 -y 100 -fs 20 -fc Yellow" -ForegroundColor Yellow
Write-Host "  watermark.exe -help  (查看完整帮助)" -ForegroundColor Yellow
Write-Host ""
Write-Host "功能说明:" -ForegroundColor Cyan
Write-Host "  【命令行参数】" -ForegroundColor White
Write-Host "  -text  | -t     水印文字(\\n换行)" -ForegroundColor Gray
Write-Host "  -x | -y         窗口位置" -ForegroundColor Gray
Write-Host "  -width | -w     窗口宽度" -ForegroundColor Gray
Write-Host "  -height | -h    窗口高度" -ForegroundColor Gray
Write-Host "  -opacity | -o   透明度(0.1-1.0)" -ForegroundColor Gray
Write-Host "  -fontsize | -fs 字体大小" -ForegroundColor Gray
Write-Host "  -fontcolor | -fc 字体颜色" -ForegroundColor Gray
Write-Host ""
Write-Host "  【普通模式】" -ForegroundColor White
Write-Host "  - 双击托盘图标:显示/隐藏水印" -ForegroundColor Gray
Write-Host "  - 左键拖动水印:移动位置" -ForegroundColor Gray
Write-Host "  - 关闭窗口:最小化到托盘" -ForegroundColor Gray
Write-Host ""
Write-Host "  【编辑模式】右键托盘 → 编辑模式" -ForegroundColor Yellow
Write-Host "  - 完全退出:右键托盘 → 退出" -ForegroundColor Red
View Code

 

 

 

 

 

以上代码是需要编译后,再执行exe程序的,

如果不想生产exe程序,也可以使用PowerShell直接运行C#代码,请自行修改。

 如果还有报警、监控等需求的,可以配合任务计划、命令行等多种方式进行动态设置和执行。

posted on 2026-07-28 11:38  jack_Meng  阅读(18)  评论(0)    收藏  举报

导航