Сбой при выполнении запрошенной операции с буфером обмена system windows forms

Exception Type: ExternalException Message: Requested Clipboard operation did not succeed. Method: ThrowIfFailed Source: System.Windows.Forms Stack Trace: at System.Windows.Forms.Clipboard.
Exception Type: ExternalException

Message: Requested Clipboard operation did not succeed.

Method: ThrowIfFailed

Source: System.Windows.Forms



Stack Trace:

   at System.Windows.Forms.Clipboard.ThrowIfFailed(Int32 hr)
   at System.Windows.Forms.Clipboard.SetDataObject(Object data, Boolean copy, Int32 retryTimes, Int32 retryDelay)
   at System.Windows.Forms.Clipboard.SetText(String text, TextDataFormat format)
   at System.Windows.Forms.Clipboard.SetText(String text)
   at Deerfield.Base.Controls.DataGridView.ProcessCmdKey(Message& msg, Keys keyData) in C:UsersDeveloperDesktopdeerfieldsrccoreDeerfieldDeerfield.BaseControlsDataGridView.cs:line 555
   at System.Windows.Forms.Control.ProcessCmdKey(Message& msg, Keys keyData)
   at System.Windows.Forms.Control.ProcessCmdKey(Message& msg, Keys keyData)
   at System.Windows.Forms.TextBoxBase.ProcessCmdKey(Message& msg, Keys keyData)
   at System.Windows.Forms.Control.PreProcessMessage(Message& msg)
   at System.Windows.Forms.Control.PreProcessControlMessageInternal(Control target, Message& msg)
   at System.Windows.Forms.Application.ThreadContext.PreTranslateMessage(MSG& msg)

I googled this, but I cannot get a decent answer as to why this is happening.

The MSDN documentation says that this often happens when the user switches to another application, but it does not appear that this was the case.

skaffman's user avatar

skaffman

396k96 gold badges814 silver badges768 bronze badges

asked Apr 18, 2011 at 19:41

KristenApril's user avatar

3

Having a similar problem. Found this entry,
which basically says to set retryTimes to 2 in the call:

Clipboard.SetDataObject(object data, bool copy, int retryTimes, int retryDelay)

Going to try it. Would be nice if anyone could post a reproducible test case.

BrutalDev's user avatar

BrutalDev

6,1316 gold badges62 silver badges72 bronze badges

answered Apr 26, 2011 at 18:53

WireGuy's user avatar

WireGuyWireGuy

4794 silver badges10 bronze badges

5

The root cause is likely to be that you are doing two operations, typically a copy and a paste, and assume that the clipboard will be available. What happens is, that you do a copy (to update the clipboard) and then other clipboard viewers are reacting to it when you try to paste. The defense is to have an except/sleep/retry mechanism around the paste operation, so that you can handle it gracefully. Telling the user to shut down rpdclip and such, won’t fly in a production application.
Also make sure that you’re not (ab)using the clipboard as a crutch. The clipboard is provided for the convenience of the USER, not the PROGRAMMER.

answered Oct 29, 2012 at 14:26

Chris Thornton's user avatar

Chris ThorntonChris Thornton

15.5k5 gold badges36 silver badges62 bronze badges

1

EASY! I had the same issue and fixed it.

Just open Task Manager, search for rdpclip.exe under Processes, kill it. Then, open a new task and run it again.

Picrofo Software's user avatar

answered Jan 20, 2012 at 5:13

hector's user avatar

hectorhector

691 silver badge1 bronze badge

2

I had this problem with an app but only when running it on an HP mini.

If I have C# express running so I can check the exception,

shutting down Google Chrome removes the problem.

reopening Google Chrome causes it to reappear.

But on my main 64 bit machine, no problem; and on my previous 32 bit machine, no problem either. Side effect of limited RAM perhaps?

Gerald

answered Apr 7, 2012 at 12:12

Gerald Bettridge's user avatar

It’s some other application is using Clipboard now. Find out the application monitoring Clipboard and kill the process. Works for me.

David's user avatar

David

72k17 gold badges130 silver badges172 bronze badges

answered Apr 3, 2012 at 7:49

tealcwu's user avatar

If you are using some VNC program (RealVNC) and your application use Clipboard from System.Windows.Forms.dll on main thread «The requested clipboard operation failed» will occur. This is my solution written in C# for .NET 3.5:

using System.Threading;

   var dataObject = new DataObject();
   private Clipboard()
   {
        //dataObject logic here

        Thread clipboardThread = new Thread(new ThreadStart(GetClipboard));
        clipboardThread.SetApartmentState(ApartmentState.STA);
        clipboardThread.Start();
   }

   private void GetClipboard()
   {
         Clipboard.SetDataObject(dataObject, true, 10, 100);
   }

answered Sep 21, 2018 at 7:10

Sashus's user avatar

SashusSashus

4118 silver badges8 bronze badges

I used System.Windows.Forms.Control.WndProc method and PostMessage.

string clipboardText;

{
    clipboardText = "TEXT FOR CLIPBOARD";
    PostMessage(Handle, CLIPBOARD_BACKUP_MSG, 0, 0);
}

protected override void WndProc(ref Message m) 
{
    if (m.Msg == CLIPBOARD_BACKUP_MSG)
    {
        Clipboard.SetText(clipboardText);
    }

    base.WndProc(ref m);
}

answered Sep 16, 2013 at 19:03

asavin's user avatar

1

I had this problem too, and use this code as WireGuy answered. but this code code makes an exception in my PC «Requested Clipboard operation did not succeed». I put this line a Try Catch statement

            try
            {
                Clipboard.SetDataObject(textBoxCodePan.Text, true, 10, 100);
            }
            catch (Exception)
            {

            }

and did work correctly.

answered Oct 9, 2018 at 14:52

Ali Ahmadvand's user avatar

Try running GetDataObject in while loop with Try catch. Eventually it will succeed.

    while (tempObj == null)
    {// get from the clipboard
        try
        {
            tempObj = Clipboard.GetDataObject();
        }
        catch (Exception excep)
        {

        }
    }

Eric Jin's user avatar

Eric Jin

3,7704 gold badges19 silver badges45 bronze badges

answered May 16, 2020 at 17:40

Mahesh Kale's user avatar

For myself, I found that the clipboard was still processing my request while I
was putting a new one.

SendKeys.SendWait("^c");
Clipboard.GetText();

So I added Sleep and it now works great.

SendKeys.SendWait("^c");
Thread.Sleep(250);
Clipboard.GetText();

answered Jan 24, 2015 at 22:13

Carol's user avatar

CarolCarol

1,82327 silver badges29 bronze badges

For some reason i got «Requested Clipboard operation did not succeed» exceptions every time when running

Dim s = "test"
Clipboard.SetDataObject(s, True, 10, 200)

But

Dim s = "test"
Clipboard.ContainsText()
Clipboard.SetDataObject(s, True, 10, 200)

worked every time.

However, interestingly

Try
    Dim s = "test"
    Clipboard.SetDataObject(s, True, 10, 200)
catch ex as exception
    Dim s = "test"
    Clipboard.ContainsText()
    Clipboard.SetDataObject(s, True, 10, 200)
end try

will fail on both SetDataObject calls

I’m sure its as transient error as i was setting clipboard content the other day without issue.

answered Sep 6, 2019 at 3:29

Tim Hall's user avatar

Tim HallTim Hall

1,3601 gold badge9 silver badges13 bronze badges

I suddenly had this error when copying data from Microsoft SQL Server Management Studio, since then I couldn’t copy anything.
Restarting explorer.exe process solved the issue. I guess the explorer process handles most of the clipboard action.

answered May 14, 2020 at 10:18

Sam's user avatar

Exception Type: ExternalException

Message: Requested Clipboard operation did not succeed.

Method: ThrowIfFailed

Source: System.Windows.Forms



Stack Trace:

   at System.Windows.Forms.Clipboard.ThrowIfFailed(Int32 hr)
   at System.Windows.Forms.Clipboard.SetDataObject(Object data, Boolean copy, Int32 retryTimes, Int32 retryDelay)
   at System.Windows.Forms.Clipboard.SetText(String text, TextDataFormat format)
   at System.Windows.Forms.Clipboard.SetText(String text)
   at Deerfield.Base.Controls.DataGridView.ProcessCmdKey(Message& msg, Keys keyData) in C:UsersDeveloperDesktopdeerfieldsrccoreDeerfieldDeerfield.BaseControlsDataGridView.cs:line 555
   at System.Windows.Forms.Control.ProcessCmdKey(Message& msg, Keys keyData)
   at System.Windows.Forms.Control.ProcessCmdKey(Message& msg, Keys keyData)
   at System.Windows.Forms.TextBoxBase.ProcessCmdKey(Message& msg, Keys keyData)
   at System.Windows.Forms.Control.PreProcessMessage(Message& msg)
   at System.Windows.Forms.Control.PreProcessControlMessageInternal(Control target, Message& msg)
   at System.Windows.Forms.Application.ThreadContext.PreTranslateMessage(MSG& msg)

I googled this, but I cannot get a decent answer as to why this is happening.

The MSDN documentation says that this often happens when the user switches to another application, but it does not appear that this was the case.

skaffman's user avatar

skaffman

396k96 gold badges814 silver badges768 bronze badges

asked Apr 18, 2011 at 19:41

KristenApril's user avatar

3

Having a similar problem. Found this entry,
which basically says to set retryTimes to 2 in the call:

Clipboard.SetDataObject(object data, bool copy, int retryTimes, int retryDelay)

Going to try it. Would be nice if anyone could post a reproducible test case.

BrutalDev's user avatar

BrutalDev

6,1316 gold badges62 silver badges72 bronze badges

answered Apr 26, 2011 at 18:53

WireGuy's user avatar

WireGuyWireGuy

4794 silver badges10 bronze badges

5

The root cause is likely to be that you are doing two operations, typically a copy and a paste, and assume that the clipboard will be available. What happens is, that you do a copy (to update the clipboard) and then other clipboard viewers are reacting to it when you try to paste. The defense is to have an except/sleep/retry mechanism around the paste operation, so that you can handle it gracefully. Telling the user to shut down rpdclip and such, won’t fly in a production application.
Also make sure that you’re not (ab)using the clipboard as a crutch. The clipboard is provided for the convenience of the USER, not the PROGRAMMER.

answered Oct 29, 2012 at 14:26

Chris Thornton's user avatar

Chris ThorntonChris Thornton

15.5k5 gold badges36 silver badges62 bronze badges

1

EASY! I had the same issue and fixed it.

Just open Task Manager, search for rdpclip.exe under Processes, kill it. Then, open a new task and run it again.

Picrofo Software's user avatar

answered Jan 20, 2012 at 5:13

hector's user avatar

hectorhector

691 silver badge1 bronze badge

2

I had this problem with an app but only when running it on an HP mini.

If I have C# express running so I can check the exception,

shutting down Google Chrome removes the problem.

reopening Google Chrome causes it to reappear.

But on my main 64 bit machine, no problem; and on my previous 32 bit machine, no problem either. Side effect of limited RAM perhaps?

Gerald

answered Apr 7, 2012 at 12:12

Gerald Bettridge's user avatar

It’s some other application is using Clipboard now. Find out the application monitoring Clipboard and kill the process. Works for me.

David's user avatar

David

72k17 gold badges130 silver badges172 bronze badges

answered Apr 3, 2012 at 7:49

tealcwu's user avatar

If you are using some VNC program (RealVNC) and your application use Clipboard from System.Windows.Forms.dll on main thread «The requested clipboard operation failed» will occur. This is my solution written in C# for .NET 3.5:

using System.Threading;

   var dataObject = new DataObject();
   private Clipboard()
   {
        //dataObject logic here

        Thread clipboardThread = new Thread(new ThreadStart(GetClipboard));
        clipboardThread.SetApartmentState(ApartmentState.STA);
        clipboardThread.Start();
   }

   private void GetClipboard()
   {
         Clipboard.SetDataObject(dataObject, true, 10, 100);
   }

answered Sep 21, 2018 at 7:10

Sashus's user avatar

SashusSashus

4118 silver badges8 bronze badges

I used System.Windows.Forms.Control.WndProc method and PostMessage.

string clipboardText;

{
    clipboardText = "TEXT FOR CLIPBOARD";
    PostMessage(Handle, CLIPBOARD_BACKUP_MSG, 0, 0);
}

protected override void WndProc(ref Message m) 
{
    if (m.Msg == CLIPBOARD_BACKUP_MSG)
    {
        Clipboard.SetText(clipboardText);
    }

    base.WndProc(ref m);
}

answered Sep 16, 2013 at 19:03

asavin's user avatar

1

I had this problem too, and use this code as WireGuy answered. but this code code makes an exception in my PC «Requested Clipboard operation did not succeed». I put this line a Try Catch statement

            try
            {
                Clipboard.SetDataObject(textBoxCodePan.Text, true, 10, 100);
            }
            catch (Exception)
            {

            }

and did work correctly.

answered Oct 9, 2018 at 14:52

Ali Ahmadvand's user avatar

Try running GetDataObject in while loop with Try catch. Eventually it will succeed.

    while (tempObj == null)
    {// get from the clipboard
        try
        {
            tempObj = Clipboard.GetDataObject();
        }
        catch (Exception excep)
        {

        }
    }

Eric Jin's user avatar

Eric Jin

3,7704 gold badges19 silver badges45 bronze badges

answered May 16, 2020 at 17:40

Mahesh Kale's user avatar

For myself, I found that the clipboard was still processing my request while I
was putting a new one.

SendKeys.SendWait("^c");
Clipboard.GetText();

So I added Sleep and it now works great.

SendKeys.SendWait("^c");
Thread.Sleep(250);
Clipboard.GetText();

answered Jan 24, 2015 at 22:13

Carol's user avatar

CarolCarol

1,82327 silver badges29 bronze badges

For some reason i got «Requested Clipboard operation did not succeed» exceptions every time when running

Dim s = "test"
Clipboard.SetDataObject(s, True, 10, 200)

But

Dim s = "test"
Clipboard.ContainsText()
Clipboard.SetDataObject(s, True, 10, 200)

worked every time.

However, interestingly

Try
    Dim s = "test"
    Clipboard.SetDataObject(s, True, 10, 200)
catch ex as exception
    Dim s = "test"
    Clipboard.ContainsText()
    Clipboard.SetDataObject(s, True, 10, 200)
end try

will fail on both SetDataObject calls

I’m sure its as transient error as i was setting clipboard content the other day without issue.

answered Sep 6, 2019 at 3:29

Tim Hall's user avatar

Tim HallTim Hall

1,3601 gold badge9 silver badges13 bronze badges

I suddenly had this error when copying data from Microsoft SQL Server Management Studio, since then I couldn’t copy anything.
Restarting explorer.exe process solved the issue. I guess the explorer process handles most of the clipboard action.

answered May 14, 2020 at 10:18

Sam's user avatar

SandWraith, вот:

Подробная информация об использовании оперативной
(JIT) отладки вместо данного диалогового
окна содержится в конце этого сообщения.

************** Текст исключения **************
System.Runtime.InteropServices.ExternalException: Сбой при выполнении запрошенной операции с буфером обмена.
в System.Windows.Forms.Clipboard.ThrowIfFailed(Int32 hr)
в System.Windows.Forms.Clipboard.SetDataObject(Objec t data, Boolean copy, Int32 retryTimes, Int32 retryDelay)
в System.Windows.Forms.Clipboard.SetText(String text, TextDataFormat format)
в MyProgram.MainWindow.copyButton_Click(Object sender, EventArgs e)
в System.Windows.Forms.Control.OnClick(EventArgs e)
в System.Windows.Forms.Button.OnClick(EventArgs e)
в System.Windows.Forms.Button.OnMouseUp(MouseEventAr gs mevent)
в System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
в System.Windows.Forms.Control.WndProc(Message& m)
в System.Windows.Forms.ButtonBase.WndProc(Message& m)
в System.Windows.Forms.Button.WndProc(Message& m)
в System.Windows.Forms.Control.ControlNativeWindow.O nMessage(Message& m)
в System.Windows.Forms.Control.ControlNativeWindow.W ndProc(Message& m)
в System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

************** Загруженные сборки **************
mscorlib
Версия сборки: 2.0.0.0
Версия Win32: 2.0.50727.3615 (GDR.050727-3600)
CodeBase: file:///C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/mscorlib.dll
—————————————-
MyProgram
Версия сборки: 1.2.0.0
Версия Win32: 1.2.0.0
CodeBase: file:///E:/MyProgram/MyProgram.exe
—————————————-
System.Windows.Forms
Версия сборки: 2.0.0.0
Версия Win32: 2.0.50727.3053 (netfxsp.050727-3000)
CodeBase: file:///C:/WINDOWS/assembly/GAC_MSIL/System.Windows.Forms/2.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
—————————————-
System
Версия сборки: 2.0.0.0
Версия Win32: 2.0.50727.3614 (GDR.050727-3600)
CodeBase: file:///C:/WINDOWS/assembly/GAC_MSIL/System/2.0.0.0__b77a5c561934e089/System.dll
—————————————-
System.Drawing
Версия сборки: 2.0.0.0
Версия Win32: 2.0.50727.3053 (netfxsp.050727-3000)
CodeBase: file:///C:/WINDOWS/assembly/GAC_MSIL/System.Drawing/2.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
—————————————-
System.Windows.Forms.resources
Версия сборки: 2.0.0.0
Версия Win32: 2.0.50727.42 (RTM.050727-4200)
CodeBase: file:///C:/WINDOWS/assembly/GAC_MSIL/System.Windows.Forms.resources/2.0.0.0_ru_b77a5c561934e089/System.Windows.Forms.resources.dll
—————————————-
mscorlib.resources
Версия сборки: 2.0.0.0
Версия Win32: 2.0.50727.3615 (GDR.050727-3600)
CodeBase: file:///C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/mscorlib.dll
—————————————-

************** Оперативная отладка (JIT) **************
Для подключения оперативной (JIT) отладки файл .config данного
приложения или компьютера (machine.config) должен иметь
значение jitDebugging, установленное в секции system.windows.forms.
Приложение также должно быть скомпилировано с включенной
отладкой.

Например:

<configuration>
<system.windows.forms jitDebugging=»true» />
</configuration>

При включенной отладке JIT любое необрабатываемое исключение
пересылается отладчику JIT, зарегистрированному на данном компьютере,
вместо того чтобы обрабатываться данным диалоговым окном.

Добавлено через 19 часов 4 минуты
Неужели никто не знает? :

Skip to content

  • ТВикинариум
  • Форум
  • Поддержка
  • PRO
  • Войти

ФорумXpucT2022-08-18T02:06:35+03:00

Вы должны войти, чтобы создавать сообщения и темы.

Сбой при выполнении запрошенной операции с буфером обмена.

Profile photo ofcnom
Цитата: Михаил от 19.09.2021, 09:38

System.Runtime.InteropServices.ExternalException (0x800401D0): Сбой при выполнении запрошенной операции с буфером обмена.
в System.Windows.Forms.Clipboard.ThrowIfFailed(Int32 hr)
в System.Windows.Forms.Clipboard.SetDataObject(Object data, Boolean copy, Int32 retryTimes, Int32 retryDelay)
в System.Windows.Forms.Clipboard.SetText(String text, TextDataFormat format)
в ‫‬‌‫‫‪‪‭‬‏‭‎‫‭‭‫‏‍‭‬​‭‌‭‍‫‎‌‮.‌‏‍‪‍‏‮‮​‏‍‪‮‭‏‮‏‪​‭‮‍​‬‮‬‎‮(Object , ThreadExceptionEventArgs )
в System.Windows.Forms.Application.ThreadContext.OnThreadException(Exception t)
в System.Windows.Forms.Control.InvokeMarshaledCallbacks()
в System.Windows.Forms.Control.WndProc(Message& m)
в System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

System.Runtime.InteropServices.ExternalException (0x800401D0): Сбой при выполнении запрошенной операции с буфером обмена.
в System.Windows.Forms.Clipboard.ThrowIfFailed(Int32 hr)
в System.Windows.Forms.Clipboard.SetDataObject(Object data, Boolean copy, Int32 retryTimes, Int32 retryDelay)
в System.Windows.Forms.Clipboard.SetText(String text, TextDataFormat format)
в ‫‬‌‫‫‪‪‭‬‏‭‎‫‭‭‫‏‍‭‬​‭‌‭‍‫‎‌‮.‌‏‍‪‍‏‮‮​‏‍‪‮‭‏‮‏‪​‭‮‍​‬‮‬‎‮(Object , ThreadExceptionEventArgs )
в System.Windows.Forms.Application.ThreadContext.OnThreadException(Exception t)
в System.Windows.Forms.Control.InvokeMarshaledCallbacks()
в System.Windows.Forms.Control.WndProc(Message& m)
в System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

Голосуйте — палец вниз.0Голосуйте — палец вверх.0

Profile photo ofPotapovS
Цитата: Сергей от 19.09.2021, 09:39

Доброе утро ☀
У нас здороваются.
1. Версия Windows?
2. Оригинал или сборка?
3. Защитник или антивирус в системе?
4. В какой момент происходит ошибка?

Доброе утро ☀
У нас здороваются.
1. Версия Windows?
2. Оригинал или сборка?
3. Защитник или антивирус в системе?
4. В какой момент происходит ошибка?

Голосуйте — палец вниз.0Голосуйте — палец вверх.0

Profile photo ofAdler
Цитата: Adler от 19.09.2021, 10:40

Добрый день.
Какое-то стороннее ПО по работе с буфером обмена используется?

Добрый день.
Какое-то стороннее ПО по работе с буфером обмена используется?

Голосуйте — палец вниз.0Голосуйте — палец вверх.0

Profile photo ofcnom
Цитата: Михаил от 25.09.2021, 15:23

Здравствуйте. Извините за беспокойство. Ошибки больше не появляются, У меня стоит для работы с буфером обмена, стоит CLCL. Отключаю и никаких ошибок. Извините ещё раз. Спасибо за подсказку.

Здравствуйте. Извините за беспокойство. Ошибки больше не появляются, У меня стоит для работы с буфером обмена, стоит CLCL. Отключаю и никаких ошибок. Извините ещё раз. Спасибо за подсказку.

Голосуйте — палец вниз.0Голосуйте — палец вверх.0

Exception Type: ExternalException

Message: Requested Clipboard operation did not succeed.

Method: ThrowIfFailed

Source: System.Windows.Forms



Stack Trace:

   at System.Windows.Forms.Clipboard.ThrowIfFailed(Int32 hr)
   at System.Windows.Forms.Clipboard.SetDataObject(Object data, Boolean copy, Int32 retryTimes, Int32 retryDelay)
   at System.Windows.Forms.Clipboard.SetText(String text, TextDataFormat format)
   at System.Windows.Forms.Clipboard.SetText(String text)
   at Deerfield.Base.Controls.DataGridView.ProcessCmdKey(Message& msg, Keys keyData) in C:UsersDeveloperDesktopdeerfieldsrccoreDeerfieldDeerfield.BaseControlsDataGridView.cs:line 555
   at System.Windows.Forms.Control.ProcessCmdKey(Message& msg, Keys keyData)
   at System.Windows.Forms.Control.ProcessCmdKey(Message& msg, Keys keyData)
   at System.Windows.Forms.TextBoxBase.ProcessCmdKey(Message& msg, Keys keyData)
   at System.Windows.Forms.Control.PreProcessMessage(Message& msg)
   at System.Windows.Forms.Control.PreProcessControlMessageInternal(Control target, Message& msg)
   at System.Windows.Forms.Application.ThreadContext.PreTranslateMessage(MSG& msg)

Я погуглил, но не могу получить достойного ответа, почему это происходит.

В документации MSDN говорится, что это часто происходит, когда пользователь переключается на другое приложение, но не похоже, что это было так.

12 ответов

Лучший ответ

Имея аналогичную проблему. Нашел эту запись , который в основном говорит установить retryTimes в 2 в вызове:

Clipboard.SetDataObject(object data, bool copy, int retryTimes, int retryDelay)

Собираюсь попробовать. Было бы неплохо, если бы кто-нибудь мог опубликовать воспроизводимый тестовый пример.


13

BrutalDev
19 Янв 2017 в 07:59

Основная причина может заключаться в том, что вы выполняете две операции, обычно копирование и вставку, и предполагаете, что буфер обмена будет доступен. Что происходит, так это то, что вы делаете копию (для обновления буфера обмена), а затем другие средства просмотра буфера обмена реагируют на это, когда вы пытаетесь вставить. Защита заключается в наличии механизма except / sleep / retry для операции вставки, чтобы вы могли справиться с ней изящно. Указание пользователю выключить rpdclip и тому подобное в производственном приложении не сработает. Также убедитесь, что вы (ab) не используете буфер обмена как костыль. Буфер обмена предоставлен для удобства ПОЛЬЗОВАТЕЛЯ, а не ПРОГРАММАТОРА.


7

Chris Thornton
29 Окт 2012 в 18:26

ЛЕГКО! У меня была такая же проблема, и я ее исправил.

Просто откройте диспетчер задач, найдите rdpclip.exe в Processes, убейте его. Затем откройте новую задачу и запустите ее снова.


6

Picrofo Software
26 Окт 2012 в 09:52

У меня была эта проблема с приложением, но только при запуске на HP mini.

Если у меня запущен экспресс C #, чтобы я мог проверить исключение,

Завершение работы Google Chrome устраняет проблему.

Повторное открытие Google Chrome вызывает его повторное появление.

Но на моей основной 64-битной машине проблем нет; и на моей предыдущей 32-битной машине тоже никаких проблем. Возможно, побочный эффект ограниченного ОЗУ?

Джеральд


4

Gerald Bettridge
7 Апр 2012 в 16:12

Буфер обмена сейчас используется в другом приложении. Найдите приложение, отслеживающее буфер обмена, и завершите процесс. Работает для меня.


3

David
28 Окт 2012 в 20:01

Я использовал метод System.Windows.Forms.Control.WndProc и PostMessage.

string clipboardText;

{
    clipboardText = "TEXT FOR CLIPBOARD";
    PostMessage(Handle, CLIPBOARD_BACKUP_MSG, 0, 0);
}

protected override void WndProc(ref Message m) 
{
    if (m.Msg == CLIPBOARD_BACKUP_MSG)
    {
        Clipboard.SetText(clipboardText);
    }

    base.WndProc(ref m);
}


1

asavin
16 Сен 2013 в 23:03

У меня тоже была эта проблема, и я использую этот код в качестве ответа WireGuy. но этот код делает исключение на моем ПК «Запрошенная операция буфера обмена не удалась». Я помещаю эту строку в инструкцию Try Catch

            try
            {
                Clipboard.SetDataObject(textBoxCodePan.Text, true, 10, 100);
            }
            catch (Exception)
            {

            }

И работал правильно.


1

Ali Ahmadvand
9 Окт 2018 в 17:52

Попробуйте запустить GetDataObject в цикле while с помощью команды Try catch. В конце концов все получится.

    while (tempObj == null)
    {// get from the clipboard
        try
        {
            tempObj = Clipboard.GetDataObject();
        }
        catch (Exception excep)
        {

        }
    }


1

Eric Jin
17 Май 2020 в 07:12

Для себя я обнаружил, что буфер обмена все еще обрабатывает мой запрос, пока я ставил новую. <код> SendKeys.SendWait («^ c»); Буфер обмена.GetText ();

Итак, я добавил Sleep, и теперь он отлично работает. <код> SendKeys.SendWait («^ c»); Thread.Sleep (250); Буфер обмена.GetText ();


0

Carol
25 Янв 2015 в 01:13

По какой-то причине я получал исключения «Запрошенная операция буфера обмена не удалась» каждый раз при запуске

Dim s = "test"
Clipboard.SetDataObject(s, True, 10, 200)

Но

Dim s = "test"
Clipboard.ContainsText()
Clipboard.SetDataObject(s, True, 10, 200)

Работал каждый раз.

Однако интересно

Try
    Dim s = "test"
    Clipboard.SetDataObject(s, True, 10, 200)
catch ex as exception
    Dim s = "test"
    Clipboard.ContainsText()
    Clipboard.SetDataObject(s, True, 10, 200)
end try

Потерпит неудачу при обоих вызовах SetDataObject

Я уверен, что это такая же временная ошибка, поскольку на днях я без проблем устанавливал содержимое буфера обмена.


0

Tim Hall
6 Сен 2019 в 06:29

У меня внезапно возникла эта ошибка при копировании данных из Microsoft SQL Server Management Studio, с тех пор я ничего не мог скопировать. Перезапуск процесса explorer.exe решил проблему. Я предполагаю, что процесс проводника обрабатывает большую часть действий с буфером обмена.


0

Sam
14 Май 2020 в 13:18

Если вы используете какую-либо программу VNC (RealVNC), а ваше приложение использует буфер обмена из System.Windows.Forms.dll в основном потоке, произойдет сбой запрошенной операции с буфером обмена. Это мое решение, написанное на C # для .NET 3.5:

using System.Threading;

   var dataObject = new DataObject();
   private Clipboard()
   {
        //dataObject logic here

        Thread clipboardThread = new Thread(new ThreadStart(GetClipboard));
        clipboardThread.SetApartmentState(ApartmentState.STA);
        clipboardThread.Start();
   }

   private void GetClipboard()
   {
         Clipboard.SetDataObject(dataObject, true, 10, 100);
   }


2

Sashus
21 Сен 2018 в 10:10

I googled this question to see what I’d see, and a lot of people have asked this question, and none of them have gotten a solid answer…

So I went to the MSDN documentation and found a note that explains what most people who have asked this question describe… The symptom usually appears when the user switches to another application while the code is running. The note is quoted below, with the link to the documentation following:

All Windows-based applications share
the system Clipboard, so the contents
are subject to change when you switch
to another application.

An object must be serializable for it
to be put on the Clipboard. If you
pass a non-serializable object to a
Clipboard method, the method will fail
without throwing an exception. See
System.Runtime.Serialization for more
information on serialization. If your
target application requires a very
specific data format, the headers
added to the data in the serialization
process may prevent the application
from recognizing your data. To
preserve your data format, add your
data as a Byte array to a MemoryStream
and pass the MemoryStream to the
SetData method.

The Clipboard class can only be used
in threads set to single thread
apartment (STA) mode. To use this
class, ensure that your Main method is
marked with the STAThreadAttribute
attribute.

Special considerations may be
necessary when using the metafile
format with the Clipboard. Due to a
limitation in the current
implementation of the DataObject
class, the metafile format used by the
.NET Framework may not be recognized
by applications that use an older
metafile format. In this case, you
must interoperate with the Win32
Clipboard application programming
interfaces (APIs). For more
information, see article 323530,
«Metafiles on Clipboard Are Not
Visible to All Applications,» in the
Microsoft Knowledge Base at
http://support.microsoft.com.

http://msdn.microsoft.com/en-us/library/system.windows.forms.clipboard.aspx

Funnily enough, this makes sense of a strange behavior I noticed in one of my own apps. I have an app that writes to an Excel spreadsheet (actually, to hundreds of them, modifying hundreds of cells each). I don’t use the clipboard at all, just the Interop API for excel, yet when it’s running, my clipboard clears every time a new spreadsheet is created. In my case, Excel is messing with the clipboard, even there is no discernible reason for it to do so. I’d chalk it up to one of those mysterious Windows phenomena that we mortals will never understand.

At any rate, thanks to your question, I think I understand my issue, so +1 to you for helping me out.

Понравилась статья? Поделить с друзьями:
  • Сборка windows 10 ltsb скачать торрент
  • Сбой запроса дескриптора устройства usb windows 10 android
  • Сборка windows 7 с драйверами usb
  • Сбой при входе в учетную запись майкрософт в windows 10
  • Сборка windows 10 home без лишнего хлама