Reputation: 201
bool hasCopiedArtikelnum = false;
while (hasCopiedArtikelnum == false)
{
try
{
artikelnum = Clipboard.GetText();
hasCopiedArtikelnum = true;
}
catch {}
}
I want the program to keep looping until he has successfully copied. Does putting other things in the "try" work? Or will the programm also >>try<< to set hasCopiedArtikelnum to true?
Upvotes: 0
Views: 1894
Reputation: 176159
It seems what you really want to do is wait until the user has copied something to the clipboard and then check whether there is text contained in the clipboard using Clipboard.ContainsText
(as already suggested by @CodeCaster and @PatrickHofman).
You can receive clipboard events as described in an answer to this question: Clipboard event C#.
Such an approach is much better because you a) won't be using exceptions for control flow and b) reduce CPU load significantly by avoiding to permanent polling of the clipboard.
Upvotes: 5
Reputation: 156948
Yes, you can catch all exceptions using catch (Exception) {}
and it will continue. I advice to use a maximum number of tried though, to prevent this action from hanging.
I guess you are solving a problem with retrieving text. Maybe there are other ways to do so, maybe you can sleep for X milliseconds, use a timer to do it once a X seconds for example, etc. I guess there is another solution you are looking for. This code will hang your process until it succeeds retrieving the text. Are you looking for some event maybe?
Also it is better not to rely on an exception if you can, possibly while (!Clipboard.ContainsText(TextDataFormat.Text))
, as CodeCaster suggested it a better solution.
Upvotes: 2
Reputation: 9561
The while
loop while continue to execute until hasCopiedArtikelnum
is true.
This means you can put anything into the try
block and it will keep iterating until everything completes, at long as hasCopiedArtikelnum = true
is at the end.
If Clipboard.GetText()
throws an exception when it's not ready to complete, the execution will jump hasCopiedArtikelnum
and it will remain false
Upvotes: 3