Visual Studio Editor: Remove Structured IF/End If - visual-studio

Is there and easy way to remove the IF/End If structured pairing.
Being able to do this in one keystroke would be nice (I also use Refactor! Pro)
Right now this is what I do:
Delete the IF line
Watch Visual Studio reformat the code to line up correctly taking into account that the IF is Missing.
Navigate to the End If
Delete the End If line
i.e. In the following example I want to change the code from
IF Value = True Then
DoSomething()
DoSomething2()
End IF
To
DoSomething()
DoSomething2()

While this is not a literal refactoring in the sense specified by Martin Fowler's book Refactoring, This is how I use resharper to achieve this goal:
Move/click on like with if statement
Press control + delete to delete the line
Press Alt + enter, and the option remove braces will be the first one specified.
Press enter
Done. Not quite simple, but the keystrokes are short, and not too complicated, and I don't have to spend/waste time with dumb arrow keys or the mouse to accomplish this type of code change.
Resharper supports VB.net code as of 4.0, I believe.

Related

Get outside parentheses in Visual Studio 2013

All right, this is stupid, but I have no clue how people deal with this and I'm hoping I'm missing something...
When I write something like this:
if (n == 0)
...The closing parenthesis gets added as soon as I type the opening one. The only way I know of to get out of them now is to reach over and tap the End key or something, which kind of ... Damages my shui, you know? And yet apparently they thought this feature was a cool idea, so...
What do you normally do to tell the IDE that you're done with this bit and you're ready to move on to the next? Same question applies to automatic quotes and stuff in the XAML editor, I guess.
Just keep typing - if you type your own ) when the cursor is just before the automatic one, it should not create another ), but just move the cursor over it.
(Disclaimer: I'm not certain this works on a vanilla Visual Studio - I have a bunch of extensions installed)
You can press Ctrl + Shift + Enter to open a new line below the current one without moving the cursor to the end of the line.
To add to this, Tab is another option and I find it easier:
In your example, type the logic, press Tab to skip passed the end bracket.
If you are inside auto quotes, type your text, then press Tab twice.
Like the other answer, it only applies when first being typed, so if you go back to edit something, you are left using the End and Arrow keys.
In Visual Studio 2015 with Productivity Power Tools installed (probably works earlier as well), when being inside an auto-complete block (quotes or braces):
end goes to line end ( typically slow to type/find)
"/) typing same key as auto-complete already inserted will simply replace the auto-inserted character
tab jumps over end of auto-complete (e. g. braces or quotes)
shift+enter adds ; at end of line, goes to new line (often what you want)
ctrl+shift+enter goes to new line
There is a short key in VS - "Edit.LineEnd" - pressing "End" you get to the end of the current line. I've re-assigned it (for me the best variant was "Alt-Enter") and use it to get outside of parentheses and quotes.
Hit the enter key when you are done typing.

Does anyone know a visual studio keyboard short cut to swap around two sides of a statement?

Just wondering if anyone knows the keyboard shortcut to swap around two sides of a statement. For example:
I want to swap
firstNameTextbox.Text = myData.FirstName;
to
myData.FirstName = firstNameTextbox.Text;
Does anyone know the shortcut, if there is one? Obviously I would type them out, but there is a lot of statements I need to swap, and I think a shortcut like that would be useful!
Feel free to throw in any shortcuts you think are cool!
My contribution would be CTRL + E, D - this will format your code to Visual Studio standards! Pretty well known I'm guessing but I use it all the time! :)
UPDATE
Just to let everyone know, using a bit of snooping of the article that was posted, I managed to construct a regular expression, so here it is:
Find:
{.+\.Text = myData\..+};
And replace with:
\2 = \1;
Hopefully people can apply this to their own expressions they want to swap!
I think the following thread is a good place to begin with
Invert assignment direction in Visual Studio
Here's how I would go about doing that without a specific keyboard shortcut:
First, select the text you want to modify and replace
" = " with " = "
(the key here is to add a lot of spaces).
If you hold down Alt and use the mouse, you can select a "block" of code. Use this to select only the text on the right side of the equation (it's helpful to add extra white space here in your selection)
Use the same Alt + Left-Click combination to select the beginning of the left side (just select a blank area). You should be able to paste text into here.
If you added extra white space to the text you just added, just should be able to easily insert an = using the Alt + Click technique. Use the same trick to remove the equal sign that's dangling on the right side of your code block.
While this might not do exactly what you're looking for, I've found these tricks quite useful.
If you're using ReSharper, you can do this by pressing CtrlAltShift + ← or →
The feature is in Resharper. Select the code segment and click the content wizard, which is a pencil icon in the left corner reading View Actions List, then choose Reverse Assignment.
It is done.
swap-word is a VSCode extension which sounds like it would do what you want.
Quickly swap places two words or selections...
But I'm not sure if it is compatible with VS.
Since I was not happy with the answers where I need to enter complicated strings into the Visual Studio search/replace dialog, I wrote myself a little AutoHotkey script, that performs the swaps with only the need to press a keyboard shortcut. And this, no matter if you are in VS or in another IDE.
This hotkey (start it once simply from a textfile as script or compiled to exe) runs whenever Win+Ctrl-S is pressed
#^s Up::
clipboard := "" ; Empty the clipboard
Sendinput {Ctrl down}c{ctrl up}
Clipwait
Loop, Parse, clipboard, `n, `r ; iterates over seperates lines
{
array := StrSplit(RegExReplace(A_LoopField,";",""),"=") ; remove semicolon and split by '='
SendInput, % Trim(array[2]) . " = " . Trim(array[1]) . ";{Enter}"
}
return
Many more details are possible, e.g. also supporting code where lines end with a comma
...and I can put many more hotkeys and hotstrings into the same script, e.g. for my most mistyped words:
::esle::else ; this 1 line rewrites all my 'else' typos
I recommend using the find-replace option in Visual Studio. IMHO the REGEX string is not that complicated, and moreover, you don't need to understand the expression in order to use it.
The following regex string works for most programming languages:
([\w\.]+)\s*=\s*([\w\.]+)
For Visual Studio's you want to use $ argument in the replace text.
$2 = $1
Make sure to enable regex.
To do this in one shot, you can select a section of the document, and click the replace-all option.
Before:
comboBoxAddOriginalSrcTextToComment.SelectedIndex = Settings.Default.comboBoxAddOriginalSrcTextToComment;
comboBoxDefaultLanguageSet.SelectedIndex = Settings.Default.comboBoxDefaultLanguageSet;
comboBoxItemsPerTransaltionRequest.SelectedIndex = Settings.Default.comboBoxItemsPerTransaltionRequest;
comboBoxLogFileVerbosityLevel.SelectedIndex = Settings.Default.comboBoxLogFileVerbosityLevel;
comboBoxScreenVerbosityLevel.SelectedIndex = Settings.Default.comboBoxScreenVerbosityLevel;
After:
Settings.Default.comboBoxAddOriginalSrcTextToComment = comboBoxAddOriginalSrcTextToComment.SelectedIndex;
Settings.Default.comboBoxDefaultLanguageSet = comboBoxDefaultLanguageSet.SelectedIndex;
Settings.Default.comboBoxItemsPerTransaltionRequest = comboBoxItemsPerTransaltionRequest.SelectedIndex;
Settings.Default.comboBoxLogFileVerbosityLevel = comboBoxLogFileVerbosityLevel.SelectedIndex;
Settings.Default.comboBoxScreenVerbosityLevel = comboBoxScreenVerbosityLevel.SelectedIndex;
IMHO: It's better for a developer to learn to use the IDE (Integrated Development Environment), then to create new tools to do the same thing the IDE can do.

Visual Studio - Is there a keyboard combination to select an entire line?

I already know about Ctrl + L to delete an entire line...is there one to just select an entire line (which I can then copy and paste somewhere else...)
You can also use Ctrl + X to cut an entire line. Similarly, you can use Ctrl + C to copy an entire line.
As long as you don't have anything selected, the command will work on the entire line.
Hit
Home
Shift + End
You can do it with Shift + DownArrow.
Yes there is. If you are in the begining of the line press Shift+ End.
If you are in the end of the line press Shift+ Home.
Hope that helps
I believe, if you don't have any selection and press Ctrl + C, it would copy the line.
Shift + End = Select between cursor and the end of the line
It's Home+Home, then Shift+Down for me.
Or you change that setting which makes Ctrl+C with no selection copy the line. But I hate that, so I always turn it off. (Thanks to Bala for providing the link to that setting!)
To cut a line, Ctrl+L works in my keyboard settings.
There's also Alt-Up and Alt-Down to move whole lines. It's two fewer keystrokes than using Ctrl-X, and unlike Ctrl-X, it also moves multiple whole lines at a time if your selection covers multiple lines even partially. It's also nice because the feedback is instantaneous, unlike Ctrl-X where you can never remember whether the pasted line will go above or below your cursor.
I saw this and thought I'd never use the feature. But once I got used to it I use it all the time. There's no easier way to move a block of code than using Shift-Up/Down to select the lines, press Alt-Up/Down a few times to move them, and then use Tab to adjust the indentation.
Of course it only works within the same file though.
Visual Studio macros are another way to do these types of operations if you can't find an existing command. A simple way to create one is:
Use the Record TemporaryMacro option (under Tools/Macros).
Select the line however you prefer (e.g., home, shift, end).
Click Stop Recording (under Tools/Macros).
Choose Save TemporaryMacro (under Tools/Macros).
Then choose Tools/Customize/Keyboard and assign a shortcut to the macro.
It's not specifically a keyboard shortcut, but a triple-click will select a whole line of code.
This works in some other areas of Windows as well. In Chrome, for example, double-click selects a word, but triple-click selects a paragraph.
(This works in Visual Studio 2013 on Windows 7. Not sure about other versions/platforms.)
I use Ctrl + Insert to copy entire line, and Shift + Insert to paste entire line.
Other answers require either using a mouse or hitting more than one combination.
So I've created a macro for those who want a VSCode-like Ctrl+L behaviour. It can select multiple lines.
To use it, install Visual Commander extension for macros: https://marketplace.visualstudio.com/items?itemName=SergeyVlasov.VisualCommander
Then create a new command, select C# as a language and paste this code:
using EnvDTE;
using EnvDTE80;
public class C : VisualCommanderExt.ICommand
{
public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package)
{
var ts = DTE.ActiveDocument.Selection as EnvDTE.TextSelection;
if (!ts.ActivePoint.AtStartOfLine)
ts.StartOfLine();
ts.LineDown(true, 1);
}
}
Now you can assign a desired shortcut in preferences:
Tested in VS 2022.
Triple-click to select the whole line. Then do what you want.
You can press Home + Shift + End to select the whole line as well.
If you want to copy the whole line then just press Ctrl + C. It will copy the whole line if nothing is selected.

Use of Edit.SelectToLastGoBack in Visual Studio

There is a command in Visual Studio 2005 called Edit.SelectToLastGoBack (bound to Ctrl + =).
I presume it is supposed to select all the text between the current cursor position and the last 'Go Back' point, but I can't work out the algorithm it's using for deciding what that point is.
Does anyone know how to use this potentially very useful command?
Selects to the last juimp point ...
Try using the navigation bar to jump to another method in class. Then press Ctrl + "="
It will select from the start of method you jumped to all the way back to where you jumped from.
I have yet to find a use for it though TBH,
Kindness,
Dan
I use it for recording macros.
Frequently I want to select everything from this brace to that brace and cut it in a macro. Go to the first brace, hit ctrl-f (ctrl-i doesn't work right in macros), search to the second brace, close search with escape, and hit ctrl-= to get everything between the braces selected. This is much more reliably repeatable in a macro than something like using ctrl arrows to navigate a word at a time while holding down shift, and is similar to the emacs concept of setting a mark point.
I'm not sure what all starts a new 'location in navigation history', but I'm sure starting a search does and that's all I need.
I just discovered this command is available in Visual Studio 2012. I've been looking for it ever since I got VS 2012. I kept thinking it was something like anchor, like select everything between the anchor and point. I was disappointed that macro recording and playing are no longer available. But I am glad this command still exists.
Another useful command is ctrl+k ctrl+a, which is Edit.SwapAnchor. So, you could be someplace in the code, then do a find. Now you have the point and anchor (maybe also known as the cursor and last goback). You can do ctrl+= to select, then ctrl+k ctrl+a then extend from the other end using another find--or something like that.

Hidden Features of Visual Studio (2005-2010)?

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
Visual Studio is such a massively big product that even after years of working with it I sometimes stumble upon a new/better way to do things or things I didn't even know were possible.
For instance-
Crtl + R, Ctrl + W to show white spaces. Essential for editing Python build scripts.
Under "HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\Text Editor"
Create a String called Guides with the value "RGB(255,0,0), 80" to have a red line at column 80 in the text editor.
What other hidden features have you stumbled upon?
Make a selection with ALT pressed - selects a square of text instead of whole lines.
Tracepoints!
Put a breakpoint on a line of code. Bring up the Breakpoints Window and right click on the new breakpoint. Select 'When Hit...'. By ticking the 'Print a message' check box Visual Studio will print out a message to the Debug Output every time the line of code is executed, rather than (or as well as) breaking on it. You can also get it to execute a macro as it passes the line.
You can drag code to the ToolBox. Try it!
Click an identifier (class name, variable, etc) then hit F12 for "Go To Definition". I'm always amazed how many people I watch code use the slower right-click -> "Go To Definition" method.
EDIT: Then you can use Ctrl+- to jump back to where you were.
CTRL+SHIFT+V will cycle through your clipboard, Visual Studio keeps a history of copies.
Sara Ford covers lots of lovely tips: http://blogs.msdn.com/saraford/archive/tags/Visual+Studio+2008+Tip+of+the+Day/default.aspx
But some of my favourites are Code Snippets, Ctrl + . to add a using <Namespace> or generate a method stub.
I can't live without that.
Check out a great list in the Visual Studio 2008 C# Keybinding poster: http://www.microsoft.com/downloadS/details.aspx?familyid=E5F902A8-5BB5-4CC6-907E-472809749973&displaylang=en
CTRL-K, CTRL-D
Reformat Document!
This is under the VB keybindings, not sure about C#
How many times do you debug an array in a quickwatch or a watch window and only have visual studio show you the first element? Add ",N" to the end of the definition to make studio show you the next N items as well. IE "this->m_myArray" becomes "this->m_array,5".
Incremental search: While having a source document open hit (CTRL + I) and type the word you are searching for you can hit (CTRL + I) again to see words matching your input.
You can use the following codes in the watch window.
#err - display last error
#err,hr - display last error as an HRESULT
#exception - display current exception
Ctrl-K, Ctrl-C to comment a block of text with // at the start
Ctrl-K, Ctrl-U to uncomment a block of text with // at the start
Can't live without it! :)
Stopping the debugger from stepping into trivial functions.
When you’re stepping through code in the debugger, you can spend a lot of time stepping in and out of functions you’re not particularly interested in, with names such as GetID(), or std::vector<>(), to pick a C++ example. You can use the registry to make the debugger ignore these.
For Visual Studio 2005, you have to go to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio \8.0\NativeDE\StepOver and add string values containing regular expressions for each function or set of functions you wish to exclude; e.g.
std::vector.*::.*
TextBox::GetID
You can also override these for individual exceptions. For instance, suppose you did want to step into the vector class’s destructor:
std::vector.*::\~.*=StepInto
You can find details for other versions of Visual Studio at http://blogs.msdn.com/andypennell/archive/2004/02/06/69004.aspx
Ctrl-F10: run to cursor during debugging. Took me ages to find this, and I use it all the time;
Ctrl-E, Ctrl-D: apply standard formatting (which you can define).
TAB key feature.
If you know snippet key name, write and click double Tab. for example:
Write
foreach
and then click tab key twice to
foreach (object var in collection_to_loop)
{
}
2. If you write any event, write here
Button btn = new Button();
btn.Click +=
and then click tab key twice to
private void Form1_Load(object sender, EventArgs e)
{
Button btn = new Button();
btn.Click += new EventHandler(btn_Click);
}
void btn_Click(object sender, EventArgs e)
{
throw new Exception("The method or operation is not implemented.");
}
btn_Click function write automatically
in XAML Editor, Write any event. for example:
MouseLeftButtonDown then click tab
MouseLeftButtonDown="" then click tab again
MouseLeftButtonDown="Button_MouseLeftButtonDown" in the code section Button_MouseLeftButtonDown method created.
Sara Ford has this market cornered.
http://blogs.msdn.com/saraford/default.aspx
More Visual Studio tips and tricks than you can shake a stick at.
Some others:
The Visual Studio 2005 and 2008 3-month trial editions are fully-functional, and can be used indefinitely (forever) by setting the system clock back prior to opening VS. Then, when VS is opened, set the system clock forward again so your datetimes aren't screwed up.
But that's really piracy and I can't recommend it, especially when anybody with a .edu address can get a fully-functional Pro version of VS2008 through Microsoft Dreamspark.
You can use Visual Studio to open 3rd-party executables, and browse embedded resources (dialogs, string tables, images, etc) stored within.
Debugging visualizers are not exactly a "hidden" feature but they are somewhat neglected, and super-useful, since in addition to using the provided visualizers you can roll your own for specific data sets.
Debugger's "Set Instruction Pointer" or "Set Next Statement" command.
Conditional breakpoints (as KiwiBastard noted).
You can use Quickwatch etc. to evaluate not only the value of a variable, but runtime expressions around that variable.
T4 (Text Template Transformation Toolkit). T4 is a code generator built right into Visual Studio
Custom IntelliSense dropdown height, for example displaying 50 items instead of the default which is IMO ridiculously small (8).
(To do that, just resize the dropdown next time you see it, and Visual Studio will remember the size you selected next time it opens a dropdown.)
Discovered today:
Ctrl + .
Brings up the context menu for refactoring (then one that's accessible via the underlined last letter of a class/method/property you've just renamed - mouse over for menu or "Ctrl" + ".")
A lot of people don't know or use the debugger to it's fullest - I.E. just use it to stop code, but right click on the red circle and there are a lot more options such as break on condition, run code on break.
Also you can change variable values at runtime using the debugger which is a great feature - saves rerunning code to fix a silly logic error etc.
Line transpose, Shift-Alt-T
Swaps two line (current and next) and moves cursor to the next line. I'm lovin it. I've even written a macro which changed again position by one line, executed line transpose and changed line position again so it all looking like I swapping current line with previous (Reverse line transpose).
Word transpose, Shift-Ctrl-T
When developing C++, Ctrl-F7 compiles the current file only.
Document Outline in the FormsDesigner (CTRL + ALT + T)
Fast control renaming, ordering and more!
To auto-sync current file with Solution Explorer. So don't have to look where the file lives in the project structure
Tools -> Options -> Projects and Solutions -> "Track Active Item in Solution Explorer"
Edit: If this gets too annoying for you then you can use Dan Vanderboom's macro to invoke this feature on demand through a keystroke.
(Note: Taken from the comment below by Jerry).
I'm not sure if it's "hidden", but not many people know about it -- pseudoregisters. Comes very handy when debugging, I've #ERR, hr in my watch window all the time.
Ctrl-Minus, Ctrl-Plus, navigates back and forward where you've been recently (only open files, though).
I don't use it often, but I do love:
ctrl-alt + mouse select
To select in a rectangular block, to 'block' boundaries.
As noted in comments,
alt + mouse select
Does just a plain rectangular block.
Here's something I learned (for C#):
You can move the cursor to the opening curly brace from the closing curly brace by pressing Control + ].
I learned this on an SO topic that's a dupe of this one:
“Hidden Secrets” of the Visual Studio .NET debugger?
CTRL + Shift + U -> Uppercase highlighted section.
CTRL + U -> Lowercase the highlighted section
Great for getting my SQL Statements looking just right when putting them into string queries.
Also useful for code you've found online where EVERYTHING IS IN CAPS.
Middle Mouse Button Click on the editor tab closes the tab.
To display any chunk of data as an n-byte "array", use the following syntax in Visual Studio's QuickWatch window:
variable, n
For example, to view a variable named foo as a 256-byte array, enter the following expression in the QuickWatch window:
foo, 256
This is particularly useful when viewing strings that aren't null-terminated or data that's only accessible via a pointer. You can use Visual Studio's Memory window to achieve a similar result, but using the QuickWatch window is often more convenient for a quick check.

Resources