English 中文(简体)
Copy/Paste in Windows Forms with custom controls
原标题:

I am writing a small application in C# using Windows Forms. I want to let my users copy and paste data around the application and there are some custom controls, for example one is a colour picker.

Some of the default controls (well at least the TextBox) have a copy and paste functionality already. I want to have the same thing with my colour picker, and also want an Edit menu at the top to copy and paste.

At the moment, I can t see how to do this in a nice way, my current tack is to catch the Ctrl + C and Ctrl + V commands and the menu clicks and go through a function which uses some Win32 calls to find the focused control and then copy or paste data from or to the control (with a massive if statement depending on the type of the focused control).

The alternative seems to be to write key handling into every custom control, but with this method I m not sure how to incorporate the Edit menu functions.

How do I do this in an elegant or more standard way?

最佳回答

The simplest way is to activate KeyPreview in the form and then follow the logic in KeyDown event.

But an other approach can be useful:
If you have in your win application a menu (by e.g. &Edit => Copy (Paste)).

Enable for that menus the keyboard shortcuts

// 
// editToolStripMenuItem
// 
this.editToolStripMenuItem.DropDownItems.AddRange(new 
System.Windows.Forms.ToolStripItem[] {
this.copyToolStripMenuItem,
this.pasteToolStripMenuItem});
this.editToolStripMenuItem.Text = "Edit";
// 
// copyToolStripMenuItem
// 
**this.copyToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)
((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C)));**
this.copyToolStripMenuItem.Text = "&Copy";
// 
// pasteToolStripMenuItem
// 
**this.pasteToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)
((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.V)));**
this.pasteToolStripMenuItem.Text = "&Paste";

So you have your shortcuts to Copy paste. Now manage just your menu clicks

private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
    Image myData = this.ActiveControl.BackgroundImage;
    Clipboard.SetImage(myData);
}

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
    Image myData = Clipboard.GetImage();
    this.ActiveControl.BackgroundImage = myData;
}

Surely, you can make invisible your menu, if you want do not show it to the user.

=============================================================================== UPDATE

code for multiple controls:

    private void copyToolStripMenuItem_Click(object sender, EventArgs e)
    {
        ICopyPasteable control = sender as ICopyPasteable;
        if (control != null)
        {
            control.CopyToClipboard();
        }
    }

    private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
    {
        ICopyPasteable control = sender as ICopyPasteable;
        if (control != null)
        {
            control.PasteFromClipboard();
        }
    }
}


public interface ICopyPasteable
{
    void CopyToClipboard();
    void PasteFromClipboard();
}

public class MyTextBox : TextBox, ICopyPasteable
{

    #region ICopyPasteable Membres

    public void CopyToClipboard()
    {
        Clipboard.SetText(this.Text);
    }

    public void PasteFromClipboard()
    {
        if (Clipboard.ContainsText())
        {
            this.Text = Clipboard.GetText();
        }
    }

    #endregion
}
问题回答

To find the focussed control: ContainerControl.ActiveControl. Then depending on the type of control, you can set a value (with the clipboard value).

The KeyUp event solved my problem! Events KeyDown and KeyPress didn t catch Ctrl + C for copy!

From Stack Overflow question Catching Ctrl + C in a textbox:

private void txtConsole_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyData == (Keys.C | Keys.Control))
    {
        _consolePort.Write(new byte[] { 3 }, 0, 1);
        e.Handled = true;
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace notep
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void b1_Click(object sender, RoutedEventArgs e)//copy
        {
            Clipboard.SetText(richTextBox1.Selection.Text);
            richTextBox1.Selection.Text = string.Empty;

        }

        private void b2_Click(object sender, RoutedEventArgs e)//cut
        {
            Clipboard.SetText(richTextBox1.Selection.Text);
        }

        private void b3_Click(object sender, RoutedEventArgs e)
        {

         richTextBox1.Selection.Text =richTextBox1.Selection.Text + Clipboard.GetText();//paste
        }
    }
}




相关问题
Bring window to foreground after Mutex fails

I was wondering if someone can tell me what would be the best way to bring my application to the foreground if a mutex was not able to be created for a new instance. E.g.: Application X is running ...

How to start WinForm app minimized to tray?

I ve successfully created an app that minimizes to the tray using a NotifyIcon. When the form is manually closed it is successfully hidden from the desktop, taskbar, and alt-tab. The problem occurs ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

Handle DataTable.DataRow cell change event

I have a DataTable that has several DataColumns and DataRow. Now i would like to handle an event when cell of this DataRow is changed. How to do this in c#?

Apparent Memory Leak in DataGridView

How do you force a DataGridView to release its reference to a bound DataSet? We have a rather large dataset being displayed in a DataGridView and noticed that resources were not being freed after the ...

ALT Key Shortcuts Hidden

I am using VS2008 and creating forms. By default, the underscore of the character in a textbox when using an ampersand is not shown when I run the application. ex. "&Goto Here" is not ...

WPF-XAML window in Winforms Application

I have a Winforms application coded in VS C# 2008 and want to insert a WPF window into the window pane of Winforms application. Could you explain me how this is done.

热门标签