Paweł Poręba
Paweł Poręba

Reputation: 1105

Cleared Clipboard is not null

I want to check if the Clipboard consists of a data and if not, let the "Paste" Button be enabled. But unfortunately, even after I clear the Clipboard it still doesn't show it's null. I am working with Windows Forms.

I manually clear the clipboard:

private void button2_Click(object sender, EventArgs e)
        {
            Clipboard.Clear();
        }

and then I add the following code to the Form LoadEvent:

if (Clipboard.GetDataObject() != null)
            {
                this.pn1_BtnPaste.Enabled = true;                  
            }

And it makes a button enabled which is weird to me. Can anybody explain why is that happening?

EDIT: Because I got understood wrong, let me change the code to make it more clear:

 private void button2_Click(object sender, EventArgs e)
        {
            Clipboard.Clear();

            if (Clipboard.GetDataObject() != null)
            {
                this.pn1_BtnPaste.Enabled = true;
            }
            else
                this.pn1_BtnPaste.Enabled = false;
        }

I click the "button2" and the "pn1_BtnPaste" is enabled anyway.

Upvotes: 1

Views: 278

Answers (1)

Hans Passant
Hans Passant

Reputation: 941208

Data can appear on the clipboard at any time. The Application.Idle event is a decent way to update the button state:

    public Form1() {
        InitializeComponent();
        Application.Idle += Application_Idle;
    }

You have to unsubscribe it again when the window closes to be on the safe side:

    protected override void OnFormClosed(FormClosedEventArgs e) {
        Application.Idle -= Application_Idle;
        base.OnFormClosed(e);
    }

Clipboard.GetDataObject() does not work the way you think it does, it never returns null. If you want to handle any data then you can write the event handler like this:

    private void Application_Idle(object sender, EventArgs e) {
        PasteButton.Enabled = Clipboard.GetDataObject().GetFormats().Length > 0;
    }

But it is pretty likely you'll find out that handling every possible format is lot let practical than you assumed.

Upvotes: 1

Related Questions