[Tex/LaTex] Background color for the caption of a listing

backgroundscaptionscolor

I'm considering this piece of code

\lstinputlisting[
  language=C,
  breaklines=true,
  basicstyle=\scriptsize\ttfamily,
  numbers=none,
  caption=\colorbox{mylightgray}\parbox{\textwidth}{\texttt{\detokenize{#1}}},
  %title=\small\texttt\lstname,
  frame=none]{#1}

why this use of parbox gives me an error? How I can have a caption in a box with a specific background color that spans for the entire \textwidth?

Best Answer

Here's another approach using the features provided by the caption package to define a new format for listing captions:

\documentclass{article}
\usepackage{caption}
\usepackage{xcolor}
\usepackage{listings}

\DeclareCaptionFormat{myformat}{%
  \colorbox{red!30}{\parbox{\dimexpr\textwidth-2\fboxsep-2\fboxrule\relax}{#1#2\ttfamily#3}}
} 
\captionsetup[lstlisting]{format=myformat}

\begin{document}

\begin{lstlisting}[caption={A colored caption}]
test
\end{lstlisting}

\end{document}

enter image description here